提交FairyGUI

This commit is contained in:
PC-20230316NUNE\Administrator
2024-10-15 20:37:54 +08:00
parent ef1d3dfb2f
commit 9cd469b811
409 changed files with 66228 additions and 4076 deletions

View File

@@ -0,0 +1,455 @@
using System;
using System.Text;
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class ByteBuffer
{
/// <summary>
///
/// </summary>
public bool littleEndian;
/// <summary>
///
/// </summary>
public string[] stringTable;
/// <summary>
///
/// </summary>
public int version;
int _pointer;
int _offset;
int _length;
byte[] _data;
static byte[] temp = new byte[8];
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="offset"></param>
/// <param name="length"></param>
public ByteBuffer(byte[] data, int offset = 0, int length = -1)
{
_data = data;
_pointer = 0;
_offset = offset;
if (length < 0)
_length = data.Length - offset;
else
_length = length;
littleEndian = false;
}
/// <summary>
///
/// </summary>
public int position
{
get { return _pointer; }
set { _pointer = value; }
}
/// <summary>
///
/// </summary>
public int length
{
get { return _length; }
}
/// <summary>
///
/// </summary>
public bool bytesAvailable
{
get { return _pointer < _length; }
}
/// <summary>
///
/// </summary>
public byte[] buffer
{
get { return _data; }
set
{
_data = value;
_pointer = 0;
_offset = 0;
_length = _data.Length;
}
}
/// <summary>
///
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public int Skip(int count)
{
_pointer += count;
return _pointer;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public byte ReadByte()
{
return _data[_offset + _pointer++];
}
/// <summary>
///
/// </summary>
/// <param name="output"></param>
/// <param name="destIndex"></param>
/// <param name="count"></param>
/// <returns></returns>
public byte[] ReadBytes(byte[] output, int destIndex, int count)
{
if (count > _length - _pointer)
throw new ArgumentOutOfRangeException();
Array.Copy(_data, _offset + _pointer, output, destIndex, count);
_pointer += count;
return output;
}
/// <summary>
///
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
public byte[] ReadBytes(int count)
{
if (count > _length - _pointer)
throw new ArgumentOutOfRangeException();
byte[] result = new byte[count];
Array.Copy(_data, _offset + _pointer, result, 0, count);
_pointer += count;
return result;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ByteBuffer ReadBuffer()
{
int count = ReadInt();
ByteBuffer ba = new ByteBuffer(_data, _pointer, count);
ba.stringTable = stringTable;
ba.version = version;
_pointer += count;
return ba;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public char ReadChar()
{
return (char)ReadShort();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool ReadBool()
{
bool result = _data[_offset + _pointer] == 1;
_pointer++;
return result;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public short ReadShort()
{
int startIndex = _offset + _pointer;
_pointer += 2;
if (littleEndian)
return (short)(_data[startIndex] | (_data[startIndex + 1] << 8));
else
return (short)((_data[startIndex] << 8) | _data[startIndex + 1]);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public ushort ReadUshort()
{
return (ushort)ReadShort();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public int ReadInt()
{
int startIndex = _offset + _pointer;
_pointer += 4;
if (littleEndian)
return (_data[startIndex]) | (_data[startIndex + 1] << 8) | (_data[startIndex + 2] << 16) | (_data[startIndex + 3] << 24);
else
return (_data[startIndex] << 24) | (_data[startIndex + 1] << 16) | (_data[startIndex + 2] << 8) | (_data[startIndex + 3]);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public uint ReadUint()
{
return (uint)ReadInt();
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public float ReadFloat()
{
int startIndex = _offset + _pointer;
_pointer += 4;
if (littleEndian == BitConverter.IsLittleEndian)
return BitConverter.ToSingle(_data, startIndex);
else
{
temp[3] = _data[startIndex];
temp[2] = _data[startIndex + 1];
temp[1] = _data[startIndex + 2];
temp[0] = _data[startIndex + 3];
return BitConverter.ToSingle(temp, 0);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public long ReadLong()
{
int startIndex = _offset + _pointer;
_pointer += 8;
if (littleEndian)
{
int i1 = (_data[startIndex]) | (_data[startIndex + 1] << 8) | (_data[startIndex + 2] << 16) | (_data[startIndex + 3] << 24);
int i2 = (_data[startIndex + 4]) | (_data[startIndex + 5] << 8) | (_data[startIndex + 6] << 16) | (_data[startIndex + 7] << 24);
return (uint)i1 | ((long)i2 << 32);
}
else
{
int i1 = (_data[startIndex] << 24) | (_data[startIndex + 1] << 16) | (_data[startIndex + 2] << 8) | (_data[startIndex + 3]);
int i2 = (_data[startIndex + 4] << 24) | (_data[startIndex + 5] << 16) | (_data[startIndex + 6] << 8) | (_data[startIndex + 7]);
return (uint)i2 | ((long)i1 << 32);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public double ReadDouble()
{
int startIndex = _offset + _pointer;
_pointer += 8;
if (littleEndian == BitConverter.IsLittleEndian)
return BitConverter.ToDouble(_data, startIndex);
else
{
temp[7] = _data[startIndex];
temp[6] = _data[startIndex + 1];
temp[5] = _data[startIndex + 2];
temp[4] = _data[startIndex + 3];
temp[3] = _data[startIndex + 4];
temp[2] = _data[startIndex + 5];
temp[1] = _data[startIndex + 6];
temp[0] = _data[startIndex + 7];
return BitConverter.ToSingle(temp, 0);
}
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string ReadString()
{
ushort len = ReadUshort();
string result = Encoding.UTF8.GetString(_data, _offset + _pointer, len);
_pointer += len;
return result;
}
/// <summary>
///
/// </summary>
/// <param name="len"></param>
/// <returns></returns>
public string ReadString(int len)
{
string result = Encoding.UTF8.GetString(_data, _offset + _pointer, len);
_pointer += len;
return result;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public string ReadS()
{
int index = ReadUshort();
if (index == 65534) //null
return null;
else if (index == 65533)
return string.Empty;
else
return stringTable[index];
}
/// <summary>
///
/// </summary>
/// <param name="cnt"></param>
/// <returns></returns>
public string[] ReadSArray(int cnt)
{
string[] ret = new string[cnt];
for (int i = 0; i < cnt; i++)
ret[i] = ReadS();
return ret;
}
private static List<GPathPoint> helperPoints = new List<GPathPoint>();
/// <summary>
///
/// </summary>
/// <param name="result"></param>
public List<GPathPoint> ReadPath()
{
helperPoints.Clear();
int len = ReadInt();
if (len == 0)
return helperPoints;
for (int i = 0; i < len; i++)
{
GPathPoint.CurveType curveType = (GPathPoint.CurveType)ReadByte();
switch (curveType)
{
case GPathPoint.CurveType.Bezier:
helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0),
new Vector3(ReadFloat(), ReadFloat(), 0)));
break;
case GPathPoint.CurveType.CubicBezier:
helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0),
new Vector3(ReadFloat(), ReadFloat(), 0),
new Vector3(ReadFloat(), ReadFloat(), 0)));
break;
default:
helperPoints.Add(new GPathPoint(new Vector3(ReadFloat(), ReadFloat(), 0), curveType));
break;
}
}
return helperPoints;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
public void WriteS(string value)
{
int index = ReadUshort();
if (index != 65534 && index != 65533)
stringTable[index] = value;
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public Color ReadColor()
{
int startIndex = _offset + _pointer;
byte r = _data[startIndex];
byte g = _data[startIndex + 1];
byte b = _data[startIndex + 2];
byte a = _data[startIndex + 3];
_pointer += 4;
return new Color32(r, g, b, a);
}
/// <summary>
///
/// </summary>
/// <param name="indexTablePos"></param>
/// <param name="blockIndex"></param>
/// <returns></returns>
public bool Seek(int indexTablePos, int blockIndex)
{
int tmp = _pointer;
_pointer = indexTablePos;
int segCount = _data[_offset + _pointer++];
if (blockIndex < segCount)
{
bool useShort = _data[_offset + _pointer++] == 1;
int newPos;
if (useShort)
{
_pointer += 2 * blockIndex;
newPos = ReadShort();
}
else
{
_pointer += 4 * blockIndex;
newPos = ReadInt();
}
if (newPos > 0)
{
_pointer = indexTablePos + newPos;
return true;
}
else
{
_pointer = tmp;
return false;
}
}
else
{
_pointer = tmp;
return false;
}
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: f72828fa75e491f4d95f92a46b01956a
timeCreated: 1535374215
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: da6063debdf749748bac0a0029b709e5
folderAsset: yes
timeCreated: 1461773298
licenseType: Store
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,104 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class HtmlButton : IHtmlObject
{
public GComponent button { get; private set; }
public const string CLICK_EVENT = "OnHtmlButtonClick";
public static string resource;
RichTextField _owner;
HtmlElement _element;
EventCallback1 _clickHandler;
public HtmlButton()
{
if (resource != null)
{
button = UIPackage.CreateObjectFromURL(resource).asCom;
_clickHandler = (EventContext context) =>
{
_owner.DispatchEvent(CLICK_EVENT, context.data, this);
};
}
else
Debug.LogWarning("FairyGUI: Set HtmlButton.resource first");
}
public DisplayObject displayObject
{
get { return button != null ? button.displayObject : null; }
}
public HtmlElement element
{
get { return _element; }
}
public float width
{
get { return button != null ? button.width : 0; }
}
public float height
{
get { return button != null ? button.height : 0; }
}
public void Create(RichTextField owner, HtmlElement element)
{
_owner = owner;
_element = element;
if (button == null)
return;
button.onClick.Add(_clickHandler);
int width = element.GetInt("width", button.sourceWidth);
int height = element.GetInt("height", button.sourceHeight);
button.SetSize(width, height);
button.text = element.GetString("value");
}
public void SetPosition(float x, float y)
{
if (button != null)
button.SetXY(x, y);
}
public void Add()
{
if (button != null)
_owner.AddChild(button.displayObject);
}
public void Remove()
{
if (button != null && button.displayObject.parent != null)
_owner.RemoveChild(button.displayObject);
}
public void Release()
{
if (button != null)
button.RemoveEventListeners();
_owner = null;
_element = null;
}
public void Dispose()
{
if (button != null)
button.Dispose();
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 268c2d7ad77b66449b4e0e39a6d0ca15
timeCreated: 1461773298
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,207 @@
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public enum HtmlElementType
{
Text,
Link,
Image,
Input,
Select,
Object,
//internal
LinkEnd,
}
/// <summary>
///
/// </summary>
public class HtmlElement
{
public HtmlElementType type;
public string name;
public string text;
public TextFormat format;
public int charIndex;
public IHtmlObject htmlObject;
public int status; //1 hidden 2 clipped 4 added
public int space;
public Vector2 position;
Hashtable attributes;
public HtmlElement()
{
format = new TextFormat();
}
public object Get(string attrName)
{
if (attributes == null)
return null;
return attributes[attrName];
}
public void Set(string attrName, object attrValue)
{
if (attributes == null)
attributes = new Hashtable();
attributes[attrName] = attrValue;
}
public string GetString(string attrName)
{
return GetString(attrName, null);
}
public string GetString(string attrName, string defValue)
{
if (attributes == null)
return defValue;
object ret = attributes[attrName];
if (ret != null)
return ret.ToString();
else
return defValue;
}
public int GetInt(string attrName)
{
return GetInt(attrName, 0);
}
public int GetInt(string attrName, int defValue)
{
string value = GetString(attrName);
if (value == null || value.Length == 0)
return defValue;
if (value[value.Length - 1] == '%')
{
int ret;
if (int.TryParse(value.Substring(0, value.Length - 1), out ret))
return Mathf.CeilToInt(ret / 100.0f * defValue);
else
return defValue;
}
else
{
int ret;
if (int.TryParse(value, out ret))
return ret;
else
return defValue;
}
}
public float GetFloat(string attrName)
{
return GetFloat(attrName, 0);
}
public float GetFloat(string attrName, float defValue)
{
string value = GetString(attrName);
if (value == null || value.Length == 0)
return defValue;
float ret;
if (float.TryParse(value, out ret))
return ret;
else
return defValue;
}
public bool GetBool(string attrName)
{
return GetBool(attrName, false);
}
public bool GetBool(string attrName, bool defValue)
{
string value = GetString(attrName);
if (value == null || value.Length == 0)
return defValue;
bool ret;
if (bool.TryParse(value, out ret))
return ret;
else
return defValue;
}
public Color GetColor(string attrName, Color defValue)
{
string value = GetString(attrName);
if (value == null || value.Length == 0)
return defValue;
return ToolSet.ConvertFromHtmlColor(value);
}
public void FetchAttributes()
{
attributes = XMLIterator.GetAttributes(attributes);
}
public bool isEntity
{
get { return type == HtmlElementType.Image || type == HtmlElementType.Select || type == HtmlElementType.Input || type == HtmlElementType.Object; }
}
#region Pool Support
static Stack<HtmlElement> elementPool = new Stack<HtmlElement>();
public static HtmlElement GetElement(HtmlElementType type)
{
HtmlElement ret;
if (elementPool.Count > 0)
ret = elementPool.Pop();
else
ret = new HtmlElement();
ret.type = type;
if (type != HtmlElementType.Text && ret.attributes == null)
ret.attributes = new Hashtable();
return ret;
}
public static void ReturnElement(HtmlElement element)
{
element.name = null;
element.text = null;
element.htmlObject = null;
element.status = 0;
if (element.attributes != null)
element.attributes.Clear();
elementPool.Push(element);
}
public static void ReturnElements(List<HtmlElement> elements)
{
int count = elements.Count;
for (int i = 0; i < count; i++)
{
HtmlElement element = elements[i];
ReturnElement(element);
}
elements.Clear();
}
#endregion
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 7d92c6025bf750145af0e456a7fd3f33
timeCreated: 1461773298
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,126 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class HtmlImage : IHtmlObject
{
public GLoader loader { get; private set; }
RichTextField _owner;
HtmlElement _element;
bool _externalTexture;
public HtmlImage()
{
loader = (GLoader)UIObjectFactory.NewObject(ObjectType.Loader);
loader.gameObjectName = "HtmlImage";
loader.fill = FillType.ScaleFree;
loader.touchable = false;
}
public DisplayObject displayObject
{
get { return loader.displayObject; }
}
public HtmlElement element
{
get { return _element; }
}
public float width
{
get { return loader.width; }
}
public float height
{
get { return loader.height; }
}
public void Create(RichTextField owner, HtmlElement element)
{
_owner = owner;
_element = element;
int sourceWidth = 0;
int sourceHeight = 0;
NTexture texture = owner.htmlPageContext.GetImageTexture(this);
if (texture != null)
{
sourceWidth = texture.width;
sourceHeight = texture.height;
loader.texture = texture;
_externalTexture = true;
}
else
{
string src = element.GetString("src");
if (src != null)
{
PackageItem pi = UIPackage.GetItemByURL(src);
if (pi != null)
{
sourceWidth = pi.width;
sourceHeight = pi.height;
}
}
loader.url = src;
_externalTexture = false;
}
int width = element.GetInt("width", sourceWidth);
int height = element.GetInt("height", sourceHeight);
if (width == 0)
width = 5;
if (height == 0)
height = 10;
loader.SetSize(width, height);
}
public void SetPosition(float x, float y)
{
loader.SetXY(x, y);
}
public void Add()
{
_owner.AddChild(loader.displayObject);
}
public void Remove()
{
if (loader.displayObject.parent != null)
_owner.RemoveChild(loader.displayObject);
}
public void Release()
{
loader.RemoveEventListeners();
if (_externalTexture)
{
_owner.htmlPageContext.FreeImageTexture(this, loader.texture);
_externalTexture = false;
}
loader.url = null;
_owner = null;
_element = null;
}
public void Dispose()
{
if (_externalTexture)
_owner.htmlPageContext.FreeImageTexture(this, loader.texture);
loader.Dispose();
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 81871e13cb458ab4da28358d5634e082
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,117 @@
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class HtmlInput : IHtmlObject
{
public GTextInput textInput { get; private set; }
RichTextField _owner;
HtmlElement _element;
bool _hidden;
public static int defaultBorderSize = 2;
public static Color defaultBorderColor = ToolSet.ColorFromRGB(0xA9A9A9);
public static Color defaultBackgroundColor = Color.clear;
public HtmlInput()
{
textInput = (GTextInput)UIObjectFactory.NewObject(ObjectType.InputText);
textInput.gameObjectName = "HtmlInput";
textInput.verticalAlign = VertAlignType.Middle;
}
public DisplayObject displayObject
{
get { return textInput.displayObject; }
}
public HtmlElement element
{
get { return _element; }
}
public float width
{
get { return _hidden ? 0 : textInput.width; }
}
public float height
{
get { return _hidden ? 0 : textInput.height; }
}
public void Create(RichTextField owner, HtmlElement element)
{
_owner = owner;
_element = element;
string type = element.GetString("type");
if (type != null)
type = type.ToLower();
_hidden = type == "hidden";
if (!_hidden)
{
int width = element.GetInt("width", 0);
int height = element.GetInt("height", 0);
int borderSize = element.GetInt("border", defaultBorderSize);
Color borderColor = element.GetColor("border-color", defaultBorderColor);
Color backgroundColor = element.GetColor("background-color", defaultBackgroundColor);
if (width == 0)
{
width = element.space;
if (width > _owner.width / 2 || width < 100)
width = (int)_owner.width / 2;
}
if (height == 0)
height = element.format.size + 10;
textInput.textFormat = element.format;
textInput.displayAsPassword = type == "password";
textInput.maxLength = element.GetInt("maxlength", int.MaxValue);
textInput.border = borderSize;
textInput.borderColor = borderColor;
textInput.backgroundColor = backgroundColor;
textInput.SetSize(width, height);
}
textInput.text = element.GetString("value");
}
public void SetPosition(float x, float y)
{
if (!_hidden)
textInput.SetXY(x, y);
}
public void Add()
{
if (!_hidden)
_owner.AddChild(textInput.displayObject);
}
public void Remove()
{
if (!_hidden && textInput.displayObject.parent != null)
_owner.RemoveChild(textInput.displayObject);
}
public void Release()
{
textInput.RemoveEventListeners();
textInput.text = null;
_owner = null;
_element = null;
}
public void Dispose()
{
textInput.Dispose();
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: e1c8ffa51408aef45839b1d00198b819
timeCreated: 1535374215
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,113 @@

namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class HtmlLink : IHtmlObject
{
RichTextField _owner;
HtmlElement _element;
SelectionShape _shape;
EventCallback1 _clickHandler;
EventCallback1 _rolloverHandler;
EventCallback0 _rolloutHandler;
public HtmlLink()
{
_shape = new SelectionShape();
_shape.gameObject.name = "HtmlLink";
_shape.cursor = "text-link";
_clickHandler = (EventContext context) =>
{
_owner.BubbleEvent("onClickLink", _element.GetString("href"));
};
_rolloverHandler = (EventContext context) =>
{
if (_owner.htmlParseOptions.linkHoverBgColor.a > 0)
_shape.color = _owner.htmlParseOptions.linkHoverBgColor;
};
_rolloutHandler = () =>
{
if (_owner.htmlParseOptions.linkHoverBgColor.a > 0)
_shape.color = _owner.htmlParseOptions.linkBgColor;
};
}
public DisplayObject displayObject
{
get { return _shape; }
}
public HtmlElement element
{
get { return _element; }
}
public float width
{
get { return 0; }
}
public float height
{
get { return 0; }
}
public void Create(RichTextField owner, HtmlElement element)
{
_owner = owner;
_element = element;
_shape.onClick.Add(_clickHandler);
_shape.onRollOver.Add(_rolloverHandler);
_shape.onRollOut.Add(_rolloutHandler);
_shape.color = _owner.htmlParseOptions.linkBgColor;
}
public void SetArea(int startLine, float startCharX, int endLine, float endCharX)
{
if (startLine == endLine && startCharX > endCharX)
{
float tmp = startCharX;
startCharX = endCharX;
endCharX = tmp;
}
_shape.rects.Clear();
_owner.textField.GetLinesShape(startLine, startCharX, endLine, endCharX, true, _shape.rects);
_shape.Refresh();
}
public void SetPosition(float x, float y)
{
_shape.SetXY(x, y);
}
public void Add()
{
//add below _shape
_owner.AddChildAt(_shape, 0);
}
public void Remove()
{
if (_shape.parent != null)
_owner.RemoveChild(_shape);
}
public void Release()
{
_shape.RemoveEventListeners();
_owner = null;
_element = null;
}
public void Dispose()
{
_shape.Dispose();
_shape = null;
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: b2132a66ecae9cc4c99c6fbe37051723
timeCreated: 1470116309
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,150 @@
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class HtmlPageContext : IHtmlPageContext
{
Stack<IHtmlObject> _imagePool;
Stack<IHtmlObject> _inputPool;
Stack<IHtmlObject> _buttonPool;
Stack<IHtmlObject> _selectPool;
Stack<IHtmlObject> _linkPool;
public static HtmlPageContext inst = new HtmlPageContext();
static Transform _poolManager;
public HtmlPageContext()
{
_imagePool = new Stack<IHtmlObject>();
_inputPool = new Stack<IHtmlObject>();
_buttonPool = new Stack<IHtmlObject>();
_selectPool = new Stack<IHtmlObject>();
_linkPool = new Stack<IHtmlObject>();
if (Application.isPlaying && _poolManager == null)
_poolManager = Stage.inst.CreatePoolManager("HtmlObjectPool");
}
virtual public IHtmlObject CreateObject(RichTextField owner, HtmlElement element)
{
IHtmlObject ret = null;
bool fromPool = false;
if (element.type == HtmlElementType.Image)
{
if (_imagePool.Count > 0 && _poolManager != null)
{
ret = _imagePool.Pop();
fromPool = true;
}
else
ret = new HtmlImage();
}
else if (element.type == HtmlElementType.Link)
{
if (_linkPool.Count > 0 && _poolManager != null)
{
ret = _linkPool.Pop();
fromPool = true;
}
else
ret = new HtmlLink();
}
else if (element.type == HtmlElementType.Input)
{
string type = element.GetString("type");
if (type != null)
type = type.ToLower();
if (type == "button" || type == "submit")
{
if (_buttonPool.Count > 0 && _poolManager != null)
{
ret = _buttonPool.Pop();
fromPool = true;
}
else
ret = new HtmlButton();
}
else
{
if (_inputPool.Count > 0 && _poolManager != null)
{
ret = _inputPool.Pop();
fromPool = true;
}
else
ret = new HtmlInput();
}
}
else if (element.type == HtmlElementType.Select)
{
if (_selectPool.Count > 0 && _poolManager != null)
{
ret = _selectPool.Pop();
fromPool = true;
}
else
ret = new HtmlSelect();
}
//Debug.Log("from=" + fromPool);
if (ret != null)
{
//可能已经被GameObject tree deleted了不再使用
if (fromPool && ret.displayObject != null && ret.displayObject.isDisposed)
{
ret.Dispose();
return CreateObject(owner, element);
}
ret.Create(owner, element);
if (ret.displayObject != null)
ret.displayObject.home = owner.cachedTransform;
}
return ret;
}
virtual public void FreeObject(IHtmlObject obj)
{
if (_poolManager == null)
{
obj.Dispose();
return;
}
//可能已经被GameObject tree deleted了不再回收
if (obj.displayObject != null && obj.displayObject.isDisposed)
{
obj.Dispose();
return;
}
obj.Release();
if (obj is HtmlImage)
_imagePool.Push(obj);
else if (obj is HtmlInput)
_inputPool.Push(obj);
else if (obj is HtmlButton)
_buttonPool.Push(obj);
else if (obj is HtmlLink)
_linkPool.Push(obj);
if (obj.displayObject != null)
obj.displayObject.cachedTransform.SetParent(_poolManager, false);
}
virtual public NTexture GetImageTexture(HtmlImage image)
{
return null;
}
virtual public void FreeImageTexture(HtmlImage image, NTexture texture)
{
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 5454bca8f43f9094ea66614837a2c0be
timeCreated: 1461773298
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,65 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class HtmlParseOptions
{
/// <summary>
///
/// </summary>
public bool linkUnderline;
/// <summary>
///
/// </summary>
public Color linkColor;
/// <summary>
///
/// </summary>
public Color linkBgColor;
/// <summary>
///
/// </summary>
public Color linkHoverBgColor;
/// <summary>
///
/// </summary>
public bool ignoreWhiteSpace;
/// <summary>
///
/// </summary>
public static bool DefaultLinkUnderline = true;
/// <summary>
///
/// </summary>
public static Color DefaultLinkColor = new Color32(0x3A, 0x67, 0xCC, 0xFF);
/// <summary>
///
/// </summary>
public static Color DefaultLinkBgColor = Color.clear;
/// <summary>
///
/// </summary>
public static Color DefaultLinkHoverBgColor = Color.clear;
public HtmlParseOptions()
{
linkUnderline = DefaultLinkUnderline;
linkColor = DefaultLinkColor;
linkBgColor = DefaultLinkBgColor;
linkHoverBgColor = DefaultLinkHoverBgColor;
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 8e3e6e98345b46a43a4181a0790d4f30
timeCreated: 1470231110
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,387 @@
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class HtmlParser
{
public static HtmlParser inst = new HtmlParser();
protected class TextFormat2 : TextFormat
{
public bool colorChanged;
}
protected List<TextFormat2> _textFormatStack;
protected int _textFormatStackTop;
protected TextFormat2 _format;
protected List<HtmlElement> _elements;
protected HtmlParseOptions _defaultOptions;
static List<string> sHelperList1 = new List<string>();
static List<string> sHelperList2 = new List<string>();
public HtmlParser()
{
_textFormatStack = new List<TextFormat2>();
_format = new TextFormat2();
_defaultOptions = new HtmlParseOptions();
}
virtual public void Parse(string aSource, TextFormat defaultFormat, List<HtmlElement> elements, HtmlParseOptions parseOptions)
{
if (parseOptions == null)
parseOptions = _defaultOptions;
_elements = elements;
_textFormatStackTop = 0;
_format.CopyFrom(defaultFormat);
_format.colorChanged = false;
int skipText = 0;
bool ignoreWhiteSpace = parseOptions.ignoreWhiteSpace;
bool skipNextCR = false;
string text;
XMLIterator.Begin(aSource, true);
while (XMLIterator.NextTag())
{
if (skipText == 0)
{
text = XMLIterator.GetText(ignoreWhiteSpace);
if (text.Length > 0)
{
if (skipNextCR && text[0] == '\n')
text = text.Substring(1);
AppendText(text);
}
}
skipNextCR = false;
switch (XMLIterator.tagName)
{
case "b":
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
_format.bold = true;
}
else
PopTextFormat();
break;
case "i":
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
_format.italic = true;
}
else
PopTextFormat();
break;
case "u":
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
_format.underline = true;
}
else
PopTextFormat();
break;
case "strike":
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
_format.strikethrough = true;
}
else
PopTextFormat();
break;
case "sub":
{
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
_format.specialStyle = TextFormat.SpecialStyle.Subscript;
}
else
PopTextFormat();
}
break;
case "sup":
{
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
_format.specialStyle = TextFormat.SpecialStyle.Superscript;
}
else
PopTextFormat();
}
break;
case "font":
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
_format.size = XMLIterator.GetAttributeInt("size", _format.size);
string color = XMLIterator.GetAttribute("color");
if (color != null)
{
string[] parts = color.Split(',');
if (parts.Length == 1)
{
_format.color = ToolSet.ConvertFromHtmlColor(color);
_format.gradientColor = null;
_format.colorChanged = true;
}
else
{
if (_format.gradientColor == null)
_format.gradientColor = new Color32[4];
_format.gradientColor[0] = ToolSet.ConvertFromHtmlColor(parts[0]);
_format.gradientColor[1] = ToolSet.ConvertFromHtmlColor(parts[1]);
if (parts.Length > 2)
{
_format.gradientColor[2] = ToolSet.ConvertFromHtmlColor(parts[2]);
if (parts.Length > 3)
_format.gradientColor[3] = ToolSet.ConvertFromHtmlColor(parts[3]);
else
_format.gradientColor[3] = _format.gradientColor[2];
}
else
{
_format.gradientColor[2] = _format.gradientColor[0];
_format.gradientColor[3] = _format.gradientColor[1];
}
}
}
}
else if (XMLIterator.tagType == XMLTagType.End)
PopTextFormat();
break;
case "br":
AppendText("\n");
break;
case "img":
if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
{
HtmlElement element = HtmlElement.GetElement(HtmlElementType.Image);
element.FetchAttributes();
element.name = element.GetString("name");
element.format.align = _format.align;
_elements.Add(element);
}
break;
case "a":
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
_format.underline = _format.underline || parseOptions.linkUnderline;
if (!_format.colorChanged && parseOptions.linkColor.a != 0)
_format.color = parseOptions.linkColor;
HtmlElement element = HtmlElement.GetElement(HtmlElementType.Link);
element.FetchAttributes();
element.name = element.GetString("name");
element.format.align = _format.align;
_elements.Add(element);
}
else if (XMLIterator.tagType == XMLTagType.End)
{
PopTextFormat();
HtmlElement element = HtmlElement.GetElement(HtmlElementType.LinkEnd);
_elements.Add(element);
}
break;
case "input":
{
HtmlElement element = HtmlElement.GetElement(HtmlElementType.Input);
element.FetchAttributes();
element.name = element.GetString("name");
element.format.CopyFrom(_format);
_elements.Add(element);
}
break;
case "select":
{
if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
{
HtmlElement element = HtmlElement.GetElement(HtmlElementType.Select);
element.FetchAttributes();
if (XMLIterator.tagType == XMLTagType.Start)
{
sHelperList1.Clear();
sHelperList2.Clear();
while (XMLIterator.NextTag())
{
if (XMLIterator.tagName == "select")
break;
if (XMLIterator.tagName == "option")
{
if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
sHelperList2.Add(XMLIterator.GetAttribute("value", string.Empty));
else
sHelperList1.Add(XMLIterator.GetText());
}
}
element.Set("items", sHelperList1.ToArray());
element.Set("values", sHelperList2.ToArray());
}
element.name = element.GetString("name");
element.format.CopyFrom(_format);
_elements.Add(element);
}
}
break;
case "p":
if (XMLIterator.tagType == XMLTagType.Start)
{
PushTextFormat();
string align = XMLIterator.GetAttribute("align");
switch (align)
{
case "center":
_format.align = AlignType.Center;
break;
case "right":
_format.align = AlignType.Right;
break;
}
if (!IsNewLine())
AppendText("\n");
}
else if (XMLIterator.tagType == XMLTagType.End)
{
AppendText("\n");
skipNextCR = true;
PopTextFormat();
}
break;
case "ui":
case "div":
case "li":
if (XMLIterator.tagType == XMLTagType.Start)
{
if (!IsNewLine())
AppendText("\n");
}
else
{
AppendText("\n");
skipNextCR = true;
}
break;
case "html":
case "body":
//full html
ignoreWhiteSpace = true;
break;
case "head":
case "style":
case "script":
case "form":
if (XMLIterator.tagType == XMLTagType.Start)
skipText++;
else if (XMLIterator.tagType == XMLTagType.End)
skipText--;
break;
}
}
if (skipText == 0)
{
text = XMLIterator.GetText(ignoreWhiteSpace);
if (text.Length > 0)
{
if (skipNextCR && text[0] == '\n')
text = text.Substring(1);
AppendText(text);
}
}
_elements = null;
}
protected void PushTextFormat()
{
TextFormat2 tf;
if (_textFormatStack.Count <= _textFormatStackTop)
{
tf = new TextFormat2();
_textFormatStack.Add(tf);
}
else
tf = _textFormatStack[_textFormatStackTop];
tf.CopyFrom(_format);
tf.colorChanged = _format.colorChanged;
_textFormatStackTop++;
}
protected void PopTextFormat()
{
if (_textFormatStackTop > 0)
{
TextFormat2 tf = _textFormatStack[_textFormatStackTop - 1];
_format.CopyFrom(tf);
_format.colorChanged = tf.colorChanged;
_textFormatStackTop--;
}
}
protected bool IsNewLine()
{
if (_elements.Count > 0)
{
HtmlElement element = _elements[_elements.Count - 1];
if (element != null && element.type == HtmlElementType.Text)
return element.text.EndsWith("\n");
else
return false;
}
return true;
}
protected void AppendText(string text)
{
HtmlElement element;
if (_elements.Count > 0)
{
element = _elements[_elements.Count - 1];
if (element.type == HtmlElementType.Text && element.format.EqualStyle(_format))
{
element.text += text;
return;
}
}
element = HtmlElement.GetElement(HtmlElementType.Text);
element.text = text;
element.format.CopyFrom(_format);
_elements.Add(element);
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 7ddf5eb218ff0cf438894e2ceb54f494
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,107 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class HtmlSelect : IHtmlObject
{
public GComboBox comboBox { get; private set; }
public const string CHANGED_EVENT = "OnHtmlSelectChanged";
public static string resource;
RichTextField _owner;
HtmlElement _element;
EventCallback0 _changeHandler;
public HtmlSelect()
{
if (resource != null)
{
comboBox = UIPackage.CreateObjectFromURL(resource).asComboBox;
_changeHandler = () =>
{
_owner.DispatchEvent(CHANGED_EVENT, null, this);
};
}
else
Debug.LogWarning("FairyGUI: Set HtmlSelect.resource first");
}
public DisplayObject displayObject
{
get { return comboBox.displayObject; }
}
public HtmlElement element
{
get { return _element; }
}
public float width
{
get { return comboBox != null ? comboBox.width : 0; }
}
public float height
{
get { return comboBox != null ? comboBox.height : 0; }
}
public void Create(RichTextField owner, HtmlElement element)
{
_owner = owner;
_element = element;
if (comboBox == null)
return;
comboBox.onChanged.Add(_changeHandler);
int width = element.GetInt("width", comboBox.sourceWidth);
int height = element.GetInt("height", comboBox.sourceHeight);
comboBox.SetSize(width, height);
comboBox.items = (string[])element.Get("items");
comboBox.values = (string[])element.Get("values");
comboBox.value = element.GetString("value");
}
public void SetPosition(float x, float y)
{
if (comboBox != null)
comboBox.SetXY(x, y);
}
public void Add()
{
if (comboBox != null)
_owner.AddChild(comboBox.displayObject);
}
public void Remove()
{
if (comboBox != null && comboBox.displayObject.parent != null)
_owner.RemoveChild(comboBox.displayObject);
}
public void Release()
{
if (comboBox != null)
comboBox.RemoveEventListeners();
_owner = null;
_element = null;
}
public void Dispose()
{
if (comboBox != null)
comboBox.Dispose();
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: a9047de8f5e36634b9cb9d7270dfb1e8
timeCreated: 1461773298
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,24 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
/// Create->SetPosition->(Add<->Remove)->Release->Dispose
/// </summary>
public interface IHtmlObject
{
float width { get; }
float height { get; }
DisplayObject displayObject { get; }
HtmlElement element { get; }
void Create(RichTextField owner, HtmlElement element);
void SetPosition(float x, float y);
void Add();
void Remove();
void Release();
void Dispose();
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: d5a416822d3ee0a4d80e32f6a03ba56f
timeCreated: 1461773298
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,15 @@

namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public interface IHtmlPageContext
{
IHtmlObject CreateObject(RichTextField owner, HtmlElement element);
void FreeObject(IHtmlObject obj);
NTexture GetImageTexture(HtmlImage image);
void FreeImageTexture(HtmlImage image, NTexture texture);
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 0f24771f8977b674aa4fbf86f45e2105
timeCreated: 1461773298
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,274 @@
using System.Collections.Generic;
using System.Collections;
using UnityEngine;
namespace FairyGUI
{
public delegate void TimerCallback(object param);
/// <summary>
///
/// </summary>
public class Timers
{
public static int repeat;
public static float time;
public static bool catchCallbackExceptions = false;
Dictionary<TimerCallback, Anymous_T> _items;
Dictionary<TimerCallback, Anymous_T> _toAdd;
List<Anymous_T> _toRemove;
List<Anymous_T> _pool;
TimersEngine _engine;
GameObject gameObject;
private static Timers _inst;
public static Timers inst
{
get
{
if (_inst == null)
_inst = new Timers();
return _inst;
}
}
public Timers()
{
_inst = this;
gameObject = new GameObject("[FairyGUI.Timers]");
gameObject.hideFlags = HideFlags.HideInHierarchy;
gameObject.SetActive(true);
Object.DontDestroyOnLoad(gameObject);
_engine = gameObject.AddComponent<TimersEngine>();
_items = new Dictionary<TimerCallback, Anymous_T>();
_toAdd = new Dictionary<TimerCallback, Anymous_T>();
_toRemove = new List<Anymous_T>();
_pool = new List<Anymous_T>(100);
}
public void Add(float interval, int repeat, TimerCallback callback)
{
Add(interval, repeat, callback, null);
}
/**
* @interval in seconds
* @repeat 0 indicate loop infinitely, otherwise the run count
**/
public void Add(float interval, int repeat, TimerCallback callback, object callbackParam)
{
if (callback == null)
{
Debug.LogWarning("timer callback is null, " + interval + "," + repeat);
return;
}
Anymous_T t;
if (_items.TryGetValue(callback, out t))
{
t.set(interval, repeat, callback, callbackParam);
t.elapsed = 0;
t.deleted = false;
return;
}
if (_toAdd.TryGetValue(callback, out t))
{
t.set(interval, repeat, callback, callbackParam);
return;
}
t = GetFromPool();
t.interval = interval;
t.repeat = repeat;
t.callback = callback;
t.param = callbackParam;
_toAdd[callback] = t;
}
public void CallLater(TimerCallback callback)
{
Add(0.001f, 1, callback);
}
public void CallLater(TimerCallback callback, object callbackParam)
{
Add(0.001f, 1, callback, callbackParam);
}
public void AddUpdate(TimerCallback callback)
{
Add(0.001f, 0, callback);
}
public void AddUpdate(TimerCallback callback, object callbackParam)
{
Add(0.001f, 0, callback, callbackParam);
}
public void StartCoroutine(IEnumerator routine)
{
_engine.StartCoroutine(routine);
}
public bool Exists(TimerCallback callback)
{
if (_toAdd.ContainsKey(callback))
return true;
Anymous_T at;
if (_items.TryGetValue(callback, out at))
return !at.deleted;
return false;
}
public void Remove(TimerCallback callback)
{
Anymous_T t;
if (_toAdd.TryGetValue(callback, out t))
{
_toAdd.Remove(callback);
ReturnToPool(t);
}
if (_items.TryGetValue(callback, out t))
t.deleted = true;
}
private Anymous_T GetFromPool()
{
Anymous_T t;
int cnt = _pool.Count;
if (cnt > 0)
{
t = _pool[cnt - 1];
_pool.RemoveAt(cnt - 1);
t.deleted = false;
t.elapsed = 0;
}
else
t = new Anymous_T();
return t;
}
private void ReturnToPool(Anymous_T t)
{
t.callback = null;
_pool.Add(t);
}
public void Update()
{
float dt = Time.unscaledDeltaTime;
Dictionary<TimerCallback, Anymous_T>.Enumerator iter;
if (_items.Count > 0)
{
iter = _items.GetEnumerator();
while (iter.MoveNext())
{
Anymous_T i = iter.Current.Value;
if (i.deleted)
{
_toRemove.Add(i);
continue;
}
i.elapsed += dt;
if (i.elapsed < i.interval)
continue;
i.elapsed -= i.interval;
if (i.elapsed < 0 || i.elapsed > 0.03f)
i.elapsed = 0;
if (i.repeat > 0)
{
i.repeat--;
if (i.repeat == 0)
{
i.deleted = true;
_toRemove.Add(i);
}
}
repeat = i.repeat;
if (i.callback != null)
{
if (catchCallbackExceptions)
{
try
{
i.callback(i.param);
}
catch (System.Exception e)
{
i.deleted = true;
Debug.LogWarning("FairyGUI: timer(internal=" + i.interval + ", repeat=" + i.repeat + ") callback error > " + e.Message);
}
}
else
i.callback(i.param);
}
}
iter.Dispose();
}
int len = _toRemove.Count;
if (len > 0)
{
for (int k = 0; k < len; k++)
{
Anymous_T i = _toRemove[k];
if (i.deleted && i.callback != null)
{
_items.Remove(i.callback);
ReturnToPool(i);
}
}
_toRemove.Clear();
}
if (_toAdd.Count > 0)
{
iter = _toAdd.GetEnumerator();
while (iter.MoveNext())
_items.Add(iter.Current.Key, iter.Current.Value);
iter.Dispose();
_toAdd.Clear();
}
}
}
class Anymous_T
{
public float interval;
public int repeat;
public TimerCallback callback;
public object param;
public float elapsed;
public bool deleted;
public void set(float interval, int repeat, TimerCallback callback, object param)
{
this.interval = interval;
this.repeat = repeat;
this.callback = callback;
this.param = param;
}
}
class TimersEngine : MonoBehaviour
{
void Update()
{
Timers.inst.Update();
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: ae007a032c404234b875df43f3129117
timeCreated: 1460480288
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,136 @@
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public static class ToolSet
{
public static Color ConvertFromHtmlColor(string str)
{
if (str.Length < 7 || str[0] != '#')
return Color.black;
if (str.Length == 9)
{
//optimize:avoid using Convert.ToByte and Substring
//return new Color32(Convert.ToByte(str.Substring(3, 2), 16), Convert.ToByte(str.Substring(5, 2), 16),
// Convert.ToByte(str.Substring(7, 2), 16), Convert.ToByte(str.Substring(1, 2), 16));
return new Color32((byte)(CharToHex(str[3]) * 16 + CharToHex(str[4])),
(byte)(CharToHex(str[5]) * 16 + CharToHex(str[6])),
(byte)(CharToHex(str[7]) * 16 + CharToHex(str[8])),
(byte)(CharToHex(str[1]) * 16 + CharToHex(str[2])));
}
else
{
//return new Color32(Convert.ToByte(str.Substring(1, 2), 16), Convert.ToByte(str.Substring(3, 2), 16),
//Convert.ToByte(str.Substring(5, 2), 16), 255);
return new Color32((byte)(CharToHex(str[1]) * 16 + CharToHex(str[2])),
(byte)(CharToHex(str[3]) * 16 + CharToHex(str[4])),
(byte)(CharToHex(str[5]) * 16 + CharToHex(str[6])),
255);
}
}
public static Color ColorFromRGB(int value)
{
return new Color(((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f, 1);
}
public static Color ColorFromRGBA(uint value)
{
return new Color(((value >> 16) & 0xFF) / 255f, ((value >> 8) & 0xFF) / 255f, (value & 0xFF) / 255f, ((value >> 24) & 0xFF) / 255f);
}
public static int CharToHex(char c)
{
if (c >= '0' && c <= '9')
return (int)c - 48;
if (c >= 'A' && c <= 'F')
return 10 + (int)c - 65;
else if (c >= 'a' && c <= 'f')
return 10 + (int)c - 97;
else
return 0;
}
public static Rect Intersection(ref Rect rect1, ref Rect rect2)
{
if (rect1.width == 0 || rect1.height == 0 || rect2.width == 0 || rect2.height == 0)
return new Rect(0, 0, 0, 0);
float left = rect1.xMin > rect2.xMin ? rect1.xMin : rect2.xMin;
float right = rect1.xMax < rect2.xMax ? rect1.xMax : rect2.xMax;
float top = rect1.yMin > rect2.yMin ? rect1.yMin : rect2.yMin;
float bottom = rect1.yMax < rect2.yMax ? rect1.yMax : rect2.yMax;
if (left > right || top > bottom)
return new Rect(0, 0, 0, 0);
else
return Rect.MinMaxRect(left, top, right, bottom);
}
public static Rect Union(ref Rect rect1, ref Rect rect2)
{
if (rect2.width == 0 || rect2.height == 0)
return rect1;
if (rect1.width == 0 || rect1.height == 0)
return rect2;
float x = Mathf.Min(rect1.x, rect2.x);
float y = Mathf.Min(rect1.y, rect2.y);
return new Rect(x, y, Mathf.Max(rect1.xMax, rect2.xMax) - x, Mathf.Max(rect1.yMax, rect2.yMax) - y);
}
public static void SkewMatrix(ref Matrix4x4 matrix, float skewX, float skewY)
{
skewX = -skewX * Mathf.Deg2Rad;
skewY = -skewY * Mathf.Deg2Rad;
float sinX = Mathf.Sin(skewX);
float cosX = Mathf.Cos(skewX);
float sinY = Mathf.Sin(skewY);
float cosY = Mathf.Cos(skewY);
float m00 = matrix.m00 * cosY - matrix.m10 * sinX;
float m10 = matrix.m00 * sinY + matrix.m10 * cosX;
float m01 = matrix.m01 * cosY - matrix.m11 * sinX;
float m11 = matrix.m01 * sinY + matrix.m11 * cosX;
float m02 = matrix.m02 * cosY - matrix.m12 * sinX;
float m12 = matrix.m02 * sinY + matrix.m12 * cosX;
matrix.m00 = m00;
matrix.m10 = m10;
matrix.m01 = m01;
matrix.m11 = m11;
matrix.m02 = m02;
matrix.m12 = m12;
}
public static void RotateUV(Vector2[] uv, ref Rect baseUVRect)
{
int vertCount = uv.Length;
float xMin = Mathf.Min(baseUVRect.xMin, baseUVRect.xMax);
float yMin = baseUVRect.yMin;
float yMax = baseUVRect.yMax;
if (yMin > yMax)
{
yMin = yMax;
yMax = baseUVRect.yMin;
}
float tmp;
for (int i = 0; i < vertCount; i++)
{
Vector2 m = uv[i];
tmp = m.y;
m.y = yMin + m.x - xMin;
m.x = xMin + yMax - tmp;
uv[i] = m;
}
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 54357cad16a6ccb4ea698f76bb43527c
timeCreated: 1460480287
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,226 @@
using System.Collections.Generic;
using System.Text;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class UBBParser
{
public static UBBParser inst = new UBBParser();
string _text;
int _readPos;
public TagHandler defaultTagHandler;
public Dictionary<string, TagHandler> handlers;
public int defaultImgWidth = 0;
public int defaultImgHeight = 0;
public delegate string TagHandler(string tagName, bool end, string attr);
public UBBParser()
{
handlers = new Dictionary<string, TagHandler>();
handlers["url"] = onTag_URL;
handlers["img"] = onTag_IMG;
handlers["b"] = onTag_Simple;
handlers["i"] = onTag_Simple;
handlers["u"] = onTag_Simple;
handlers["sup"] = onTag_Simple;
handlers["sub"] = onTag_Simple;
handlers["color"] = onTag_COLOR;
handlers["font"] = onTag_FONT;
handlers["size"] = onTag_SIZE;
handlers["align"] = onTag_ALIGN;
handlers["strike"] = onTag_Simple;
}
protected string onTag_URL(string tagName, bool end, string attr)
{
if (!end)
{
if (attr != null)
return "<a href=\"" + attr + "\" target=\"_blank\">";
else
{
string href = GetTagText(false);
return "<a href=\"" + href + "\" target=\"_blank\">";
}
}
else
return "</a>";
}
protected string onTag_IMG(string tagName, bool end, string attr)
{
if (!end)
{
string src = GetTagText(true);
if (src == null || src.Length == 0)
return null;
if (defaultImgWidth != 0)
return "<img src=\"" + src + "\" width=\"" + defaultImgWidth + "\" height=\"" + defaultImgHeight + "\"/>";
else
return "<img src=\"" + src + "\"/>";
}
else
return null;
}
protected string onTag_Simple(string tagName, bool end, string attr)
{
return end ? ("</" + tagName + ">") : ("<" + tagName + ">");
}
protected string onTag_COLOR(string tagName, bool end, string attr)
{
if (!end)
return "<font color=\"" + attr + "\">";
else
return "</font>";
}
protected string onTag_FONT(string tagName, bool end, string attr)
{
if (!end)
return "<font face=\"" + attr + "\">";
else
return "</font>";
}
protected string onTag_SIZE(string tagName, bool end, string attr)
{
if (!end)
return "<font size=\"" + attr + "\">";
else
return "</font>";
}
protected string onTag_ALIGN(string tagName, bool end, string attr)
{
if (!end)
return "<p align=\"" + attr + "\">";
else
return "</p>";
}
public string GetTagText(bool remove)
{
int pos1 = _readPos;
int pos2;
StringBuilder buffer = null;
while ((pos2 = _text.IndexOf('[', pos1)) != -1)
{
if (buffer == null)
buffer = new StringBuilder();
if (_text[pos2 - 1] == '\\')
{
buffer.Append(_text, pos1, pos2 - pos1 - 1);
buffer.Append('[');
pos1 = pos2 + 1;
}
else
{
buffer.Append(_text, pos1, pos2 - pos1);
break;
}
}
if (pos2 == -1)
return null;
if (remove)
_readPos = pos2;
return buffer.ToString();
}
public string Parse(string text)
{
_text = text;
int pos1 = 0, pos2, pos3;
bool end;
string tag, attr;
string repl;
StringBuilder buffer = null;
TagHandler func;
while ((pos2 = _text.IndexOf('[', pos1)) != -1)
{
if (buffer == null)
buffer = new StringBuilder();
if (pos2 > 0 && _text[pos2 - 1] == '\\')
{
buffer.Append(_text, pos1, pos2 - pos1 - 1);
buffer.Append('[');
pos1 = pos2 + 1;
continue;
}
buffer.Append(_text, pos1, pos2 - pos1);
pos1 = pos2;
pos2 = _text.IndexOf(']', pos1);
if (pos2 == -1)
break;
if (pos2 == pos1 + 1)
{
buffer.Append(_text, pos1, 2);
pos1 = pos2 + 1;
continue;
}
end = _text[pos1 + 1] == '/';
pos3 = end ? pos1 + 2 : pos1 + 1;
tag = _text.Substring(pos3, pos2 - pos3);
_readPos = pos2 + 1;
attr = null;
repl = null;
pos3 = tag.IndexOf('=');
if (pos3 != -1)
{
attr = tag.Substring(pos3 + 1);
tag = tag.Substring(0, pos3);
}
tag = tag.ToLower();
if (handlers.TryGetValue(tag, out func))
{
repl = func(tag, end, attr);
if (repl != null)
buffer.Append(repl);
}
else if (defaultTagHandler != null)
{
repl = defaultTagHandler(tag, end, attr);
if (repl != null)
buffer.Append(repl);
else
buffer.Append(_text, pos1, pos2 - pos1 + 1);
}
else
{
buffer.Append(_text, pos1, pos2 - pos1 + 1);
}
pos1 = _readPos;
}
if (buffer == null)
{
_text = null;
return text;
}
else
{
if (pos1 < _text.Length)
buffer.Append(_text, pos1, _text.Length - pos1);
_text = null;
return buffer.ToString();
}
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 916709794f601f949962dffdb251b946
timeCreated: 1460480288
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,427 @@
using System;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
namespace FairyGUI.Utils
{
/// <summary>
/// A simplest and readonly XML class
/// </summary>
public class XML
{
public string name;
public string text;
Dictionary<string, string> _attributes;
XMLList _children;
public static XML Create(string tag)
{
XML xml = new XML();
xml.name = tag;
return xml;
}
public XML(string XmlString)
{
Parse(XmlString);
}
private XML()
{
}
public Dictionary<string, string> attributes
{
get
{
if (_attributes == null)
_attributes = new Dictionary<string, string>();
return _attributes;
}
}
public bool HasAttribute(string attrName)
{
if (_attributes == null)
return false;
return _attributes.ContainsKey(attrName);
}
public string GetAttribute(string attrName)
{
return GetAttribute(attrName, null);
}
public string GetAttribute(string attrName, string defValue)
{
if (_attributes == null)
return defValue;
string ret;
if (_attributes.TryGetValue(attrName, out ret))
return ret;
else
return defValue;
}
public int GetAttributeInt(string attrName)
{
return GetAttributeInt(attrName, 0);
}
public int GetAttributeInt(string attrName, int defValue)
{
string value = GetAttribute(attrName);
if (value == null || value.Length == 0)
return defValue;
int ret;
if (int.TryParse(value, out ret))
return ret;
else
return defValue;
}
public float GetAttributeFloat(string attrName)
{
return GetAttributeFloat(attrName, 0);
}
public float GetAttributeFloat(string attrName, float defValue)
{
string value = GetAttribute(attrName);
if (value == null || value.Length == 0)
return defValue;
float ret;
if (float.TryParse(value, out ret))
return ret;
else
return defValue;
}
public bool GetAttributeBool(string attrName)
{
return GetAttributeBool(attrName, false);
}
public bool GetAttributeBool(string attrName, bool defValue)
{
string value = GetAttribute(attrName);
if (value == null || value.Length == 0)
return defValue;
bool ret;
if (bool.TryParse(value, out ret))
return ret;
else
return defValue;
}
public string[] GetAttributeArray(string attrName)
{
string value = GetAttribute(attrName);
if (value != null)
{
if (value.Length == 0)
return new string[] { };
else
return value.Split(',');
}
else
return null;
}
public string[] GetAttributeArray(string attrName, char seperator)
{
string value = GetAttribute(attrName);
if (value != null)
{
if (value.Length == 0)
return new string[] { };
else
return value.Split(seperator);
}
else
return null;
}
public Color GetAttributeColor(string attrName, Color defValue)
{
string value = GetAttribute(attrName);
if (value == null || value.Length == 0)
return defValue;
return ToolSet.ConvertFromHtmlColor(value);
}
public Vector2 GetAttributeVector(string attrName)
{
string value = GetAttribute(attrName);
if (value != null)
{
string[] arr = value.Split(',');
return new Vector2(float.Parse(arr[0]), float.Parse(arr[1]));
}
else
return Vector2.zero;
}
public void SetAttribute(string attrName, string attrValue)
{
if (_attributes == null)
_attributes = new Dictionary<string, string>();
_attributes[attrName] = attrValue;
}
public void SetAttribute(string attrName, bool attrValue)
{
if (_attributes == null)
_attributes = new Dictionary<string, string>();
_attributes[attrName] = attrValue ? "true" : "false";
}
public void SetAttribute(string attrName, int attrValue)
{
if (_attributes == null)
_attributes = new Dictionary<string, string>();
_attributes[attrName] = attrValue.ToString();
}
public void SetAttribute(string attrName, float attrValue)
{
if (_attributes == null)
_attributes = new Dictionary<string, string>();
_attributes[attrName] = string.Format("{0:#.####}", attrValue);
}
public void RemoveAttribute(string attrName)
{
if (_attributes != null)
_attributes.Remove(attrName);
}
public XML GetNode(string selector)
{
if (_children == null)
return null;
else
return _children.Find(selector);
}
public XMLList elements
{
get
{
if (_children == null)
_children = new XMLList();
return _children;
}
}
public XMLList Elements()
{
if (_children == null)
_children = new XMLList();
return _children;
}
public XMLList Elements(string selector)
{
if (_children == null)
_children = new XMLList();
return _children.Filter(selector);
}
public XMLList.Enumerator GetEnumerator()
{
if (_children == null)
return new XMLList.Enumerator(null, null);
else
return new XMLList.Enumerator(_children.rawList, null);
}
public XMLList.Enumerator GetEnumerator(string selector)
{
if (_children == null)
return new XMLList.Enumerator(null, selector);
else
return new XMLList.Enumerator(_children.rawList, selector);
}
public void AppendChild(XML child)
{
this.elements.Add(child);
}
public void RemoveChild(XML child)
{
if (_children == null)
return;
this._children.rawList.Remove(child);
}
public void RemoveChildren(string selector)
{
if (_children == null)
return;
if (string.IsNullOrEmpty(selector))
_children.Clear();
else
_children.RemoveAll(selector);
}
static Stack<XML> sNodeStack = new Stack<XML>();
public void Parse(string aSource)
{
Reset();
XML lastOpenNode = null;
sNodeStack.Clear();
XMLIterator.Begin(aSource);
while (XMLIterator.NextTag())
{
if (XMLIterator.tagType == XMLTagType.Start || XMLIterator.tagType == XMLTagType.Void)
{
XML childNode;
if (lastOpenNode != null)
childNode = new XML();
else
{
if (this.name != null)
{
Reset();
throw new Exception("Invalid xml format - no root node.");
}
childNode = this;
}
childNode.name = XMLIterator.tagName;
childNode._attributes = XMLIterator.GetAttributes(childNode._attributes);
if (lastOpenNode != null)
{
if (XMLIterator.tagType != XMLTagType.Void)
sNodeStack.Push(lastOpenNode);
if (lastOpenNode._children == null)
lastOpenNode._children = new XMLList();
lastOpenNode._children.Add(childNode);
}
if (XMLIterator.tagType != XMLTagType.Void)
lastOpenNode = childNode;
}
else if (XMLIterator.tagType == XMLTagType.End)
{
if (lastOpenNode == null || lastOpenNode.name != XMLIterator.tagName)
{
Reset();
throw new Exception("Invalid xml format - <" + XMLIterator.tagName + "> dismatched.");
}
if (lastOpenNode._children == null || lastOpenNode._children.Count == 0)
{
lastOpenNode.text = XMLIterator.GetText();
}
if (sNodeStack.Count > 0)
lastOpenNode = sNodeStack.Pop();
else
lastOpenNode = null;
}
}
}
public void Reset()
{
if (_attributes != null)
_attributes.Clear();
if (_children != null)
_children.Clear();
this.text = null;
}
public string ToXMLString(bool includeHeader)
{
StringBuilder sb = new StringBuilder();
if (includeHeader)
sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
ToXMLString(sb, 0);
return sb.ToString();
}
void ToXMLString(StringBuilder sb, int tabs)
{
if (tabs > 0)
sb.Append(' ', tabs * 2);
if (name == "!")
{
sb.Append("<!--");
if (text != null)
{
int c = sb.Length;
sb.Append(text);
XMLUtils.EncodeString(sb, c);
}
sb.Append("-->");
return;
}
sb.Append('<').Append(name);
if (_attributes != null)
{
foreach (KeyValuePair<string, string> kv in _attributes)
{
sb.Append(' ');
sb.Append(kv.Key).Append('=').Append('\"');
int c = sb.Length;
sb.Append(kv.Value);
XMLUtils.EncodeString(sb, c, true);
sb.Append("\"");
}
}
int numChildren = _children != null ? _children.Count : 0;
if (string.IsNullOrEmpty(text) && numChildren == 0)
sb.Append("/>");
else
{
sb.Append('>');
if (!string.IsNullOrEmpty(text))
{
int c = sb.Length;
sb.Append(text);
XMLUtils.EncodeString(sb, c);
}
if (numChildren > 0)
{
sb.Append('\n');
int ctabs = tabs + 1;
for (int i = 0; i < numChildren; i++)
{
_children[i].ToXMLString(sb, ctabs);
sb.Append('\n');
}
if (tabs > 0)
sb.Append(' ', tabs * 2);
}
sb.Append("</").Append(name).Append(">");
}
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 8375f35e0c0dbc4429287ee8578f3cf1
timeCreated: 1460480288
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,485 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace FairyGUI.Utils
{
public enum XMLTagType
{
Start,
End,
Void,
CDATA,
Comment,
Instruction
}
/// <summary>
///
/// </summary>
public class XMLIterator
{
public static string tagName;
public static XMLTagType tagType;
public static string lastTagName;
static string source;
static int sourceLen;
static int parsePos;
static int tagPos;
static int tagLength;
static int lastTagEnd;
static bool attrParsed;
static bool lowerCaseName;
static StringBuilder buffer = new StringBuilder();
static Dictionary<string, string> attributes = new Dictionary<string, string>();
const string CDATA_START = "<![CDATA[";
const string CDATA_END = "]]>";
const string COMMENT_START = "<!--";
const string COMMENT_END = "-->";
public static void Begin(string source, bool lowerCaseName = false)
{
XMLIterator.source = source;
XMLIterator.lowerCaseName = lowerCaseName;
sourceLen = source.Length;
parsePos = 0;
lastTagEnd = 0;
tagPos = 0;
tagLength = 0;
tagName = null;
}
public static bool NextTag()
{
int pos;
char c;
tagType = XMLTagType.Start;
buffer.Length = 0;
lastTagEnd = parsePos;
attrParsed = false;
lastTagName = tagName;
while ((pos = source.IndexOf('<', parsePos)) != -1)
{
parsePos = pos;
pos++;
if (pos == sourceLen)
break;
c = source[pos];
if (c == '!')
{
if (sourceLen > pos + 7 && source.Substring(pos - 1, 9) == CDATA_START)
{
pos = source.IndexOf(CDATA_END, pos);
tagType = XMLTagType.CDATA;
tagName = string.Empty;
tagPos = parsePos;
if (pos == -1)
tagLength = sourceLen - parsePos;
else
tagLength = pos + 3 - parsePos;
parsePos += tagLength;
return true;
}
else if (sourceLen > pos + 2 && source.Substring(pos - 1, 4) == COMMENT_START)
{
pos = source.IndexOf(COMMENT_END, pos);
tagType = XMLTagType.Comment;
tagName = string.Empty;
tagPos = parsePos;
if (pos == -1)
tagLength = sourceLen - parsePos;
else
tagLength = pos + 3 - parsePos;
parsePos += tagLength;
return true;
}
else
{
pos++;
tagType = XMLTagType.Instruction;
}
}
else if (c == '/')
{
pos++;
tagType = XMLTagType.End;
}
else if (c == '?')
{
pos++;
tagType = XMLTagType.Instruction;
}
for (; pos < sourceLen; pos++)
{
c = source[pos];
if (Char.IsWhiteSpace(c) || c == '>' || c == '/')
break;
}
if (pos == sourceLen)
break;
buffer.Append(source, parsePos + 1, pos - parsePos - 1);
if (buffer.Length > 0 && buffer[0] == '/')
buffer.Remove(0, 1);
bool singleQuoted = false, doubleQuoted = false;
int possibleEnd = -1;
for (; pos < sourceLen; pos++)
{
c = source[pos];
if (c == '"')
{
if (!singleQuoted)
doubleQuoted = !doubleQuoted;
}
else if (c == '\'')
{
if (!doubleQuoted)
singleQuoted = !singleQuoted;
}
if (c == '>')
{
if (!(singleQuoted || doubleQuoted))
{
possibleEnd = -1;
break;
}
possibleEnd = pos;
}
else if (c == '<')
break;
}
if (possibleEnd != -1)
pos = possibleEnd;
if (pos == sourceLen)
break;
if (source[pos - 1] == '/')
tagType = XMLTagType.Void;
tagName = buffer.ToString();
if (lowerCaseName)
tagName = tagName.ToLower();
tagPos = parsePos;
tagLength = pos + 1 - parsePos;
parsePos += tagLength;
return true;
}
tagPos = sourceLen;
tagLength = 0;
tagName = null;
return false;
}
public static string GetTagSource()
{
return source.Substring(tagPos, tagLength);
}
public static string GetRawText(bool trim = false)
{
if (lastTagEnd == tagPos)
return string.Empty;
else if (trim)
{
int i = lastTagEnd;
for (; i < tagPos; i++)
{
char c = source[i];
if (!char.IsWhiteSpace(c))
break;
}
if (i == tagPos)
return string.Empty;
else
return source.Substring(i, tagPos - i).TrimEnd();
}
else
return source.Substring(lastTagEnd, tagPos - lastTagEnd);
}
public static string GetText(bool trim = false)
{
if (lastTagEnd == tagPos)
return string.Empty;
else if (trim)
{
int i = lastTagEnd;
for (; i < tagPos; i++)
{
char c = source[i];
if (!char.IsWhiteSpace(c))
break;
}
if (i == tagPos)
return string.Empty;
else
return XMLUtils.DecodeString(source.Substring(i, tagPos - i).TrimEnd());
}
else
return XMLUtils.DecodeString(source.Substring(lastTagEnd, tagPos - lastTagEnd));
}
public static bool HasAttribute(string attrName)
{
if (!attrParsed)
{
attributes.Clear();
ParseAttributes(attributes);
attrParsed = true;
}
return attributes.ContainsKey(attrName);
}
public static string GetAttribute(string attrName)
{
if (!attrParsed)
{
attributes.Clear();
ParseAttributes(attributes);
attrParsed = true;
}
string value;
if (attributes.TryGetValue(attrName, out value))
return value;
else
return null;
}
public static string GetAttribute(string attrName, string defValue)
{
string ret = GetAttribute(attrName);
if (ret != null)
return ret;
else
return defValue;
}
public static int GetAttributeInt(string attrName)
{
return GetAttributeInt(attrName, 0);
}
public static int GetAttributeInt(string attrName, int defValue)
{
string value = GetAttribute(attrName);
if (value == null || value.Length == 0)
return defValue;
int ret;
if (int.TryParse(value, out ret))
return ret;
else
return defValue;
}
public static float GetAttributeFloat(string attrName)
{
return GetAttributeFloat(attrName, 0);
}
public static float GetAttributeFloat(string attrName, float defValue)
{
string value = GetAttribute(attrName);
if (value == null || value.Length == 0)
return defValue;
float ret;
if (float.TryParse(value, out ret))
return ret;
else
return defValue;
}
public static bool GetAttributeBool(string attrName)
{
return GetAttributeBool(attrName, false);
}
public static bool GetAttributeBool(string attrName, bool defValue)
{
string value = GetAttribute(attrName);
if (value == null || value.Length == 0)
return defValue;
bool ret;
if (bool.TryParse(value, out ret))
return ret;
else
return defValue;
}
public static Dictionary<string, string> GetAttributes(Dictionary<string, string> result)
{
if (result == null)
result = new Dictionary<string, string>();
if (attrParsed)
{
foreach (KeyValuePair<string, string> kv in attributes)
result[kv.Key] = kv.Value;
}
else //这里没有先ParseAttributes再赋值给result是为了节省复制的操作
ParseAttributes(result);
return result;
}
public static Hashtable GetAttributes(Hashtable result)
{
if (result == null)
result = new Hashtable();
if (attrParsed)
{
foreach (KeyValuePair<string, string> kv in attributes)
result[kv.Key] = kv.Value;
}
else //这里没有先ParseAttributes再赋值给result是为了节省复制的操作
ParseAttributes(result);
return result;
}
static void ParseAttributes(IDictionary attrs)
{
string attrName;
int valueStart;
int valueEnd;
bool waitValue = false;
int quoted;
buffer.Length = 0;
int i = tagPos;
int attrEnd = tagPos + tagLength;
if (i < attrEnd && source[i] == '<')
{
for (; i < attrEnd; i++)
{
char c = source[i];
if (Char.IsWhiteSpace(c) || c == '>' || c == '/')
break;
}
}
for (; i < attrEnd; i++)
{
char c = source[i];
if (c == '=')
{
valueStart = -1;
valueEnd = -1;
quoted = 0;
for (int j = i + 1; j < attrEnd; j++)
{
char c2 = source[j];
if (Char.IsWhiteSpace(c2))
{
if (valueStart != -1 && quoted == 0)
{
valueEnd = j - 1;
break;
}
}
else if (c2 == '>')
{
if (quoted == 0)
{
valueEnd = j - 1;
break;
}
}
else if (c2 == '"')
{
if (valueStart != -1)
{
if (quoted != 1)
{
valueEnd = j - 1;
break;
}
}
else
{
quoted = 2;
valueStart = j + 1;
}
}
else if (c2 == '\'')
{
if (valueStart != -1)
{
if (quoted != 2)
{
valueEnd = j - 1;
break;
}
}
else
{
quoted = 1;
valueStart = j + 1;
}
}
else if (valueStart == -1)
{
valueStart = j;
}
}
if (valueStart != -1 && valueEnd != -1)
{
attrName = buffer.ToString();
if (lowerCaseName)
attrName = attrName.ToLower();
buffer.Length = 0;
attrs[attrName] = XMLUtils.DecodeString(source.Substring(valueStart, valueEnd - valueStart + 1));
i = valueEnd + 1;
}
else
break;
}
else if (!Char.IsWhiteSpace(c))
{
if (waitValue || c == '/' || c == '>')
{
if (buffer.Length > 0)
{
attrName = buffer.ToString();
if (lowerCaseName)
attrName = attrName.ToLower();
attrs[attrName] = string.Empty;
buffer.Length = 0;
}
waitValue = false;
}
if (c != '/' && c != '>')
buffer.Append(c);
}
else
{
if (buffer.Length > 0)
waitValue = true;
}
}
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 35c75485c4f537341bbc16207588f75d
timeCreated: 1461773298
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,144 @@
using System;
using System.Collections.Generic;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class XMLList
{
public List<XML> rawList;
public XMLList()
{
rawList = new List<XML>();
}
public XMLList(List<XML> list)
{
rawList = list;
}
public void Add(XML xml)
{
rawList.Add(xml);
}
public void Clear()
{
rawList.Clear();
}
public int Count
{
get { return rawList.Count; }
}
public XML this[int index]
{
get { return rawList[index]; }
}
public Enumerator GetEnumerator()
{
return new Enumerator(rawList, null);
}
public Enumerator GetEnumerator(string selector)
{
return new Enumerator(rawList, selector);
}
static List<XML> _tmpList = new List<XML>();
public XMLList Filter(string selector)
{
bool allFit = true;
_tmpList.Clear();
int cnt = rawList.Count;
for (int i = 0; i < cnt; i++)
{
XML xml = rawList[i];
if (xml.name == selector)
_tmpList.Add(xml);
else
allFit = false;
}
if (allFit)
return this;
else
{
XMLList ret = new XMLList(_tmpList);
_tmpList = new List<XML>();
return ret;
}
}
public XML Find(string selector)
{
int cnt = rawList.Count;
for (int i = 0; i < cnt; i++)
{
XML xml = rawList[i];
if (xml.name == selector)
return xml;
}
return null;
}
public void RemoveAll(string selector)
{
rawList.RemoveAll(xml => xml.name == selector);
}
public struct Enumerator
{
List<XML> _source;
string _selector;
int _index;
int _total;
XML _current;
public Enumerator(List<XML> source, string selector)
{
_source = source;
_selector = selector;
_index = -1;
if (_source != null)
_total = _source.Count;
else
_total = 0;
_current = null;
}
public XML Current
{
get { return _current; }
}
public bool MoveNext()
{
while (++_index < _total)
{
_current = _source[_index];
if (_selector == null || _current.name == _selector)
return true;
}
return false;
}
public void Erase()
{
_source.RemoveAt(_index);
_total--;
}
public void Reset()
{
_index = -1;
}
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 2f086b805cd249140987f7f3ec5b4567
timeCreated: 1460480287
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,133 @@
using System;
using System.Text;
namespace FairyGUI.Utils
{
/// <summary>
///
/// </summary>
public class XMLUtils
{
public static string DecodeString(string aSource)
{
int len = aSource.Length;
StringBuilder sb = new StringBuilder();
int pos1 = 0, pos2 = 0;
while (true)
{
pos2 = aSource.IndexOf('&', pos1);
if (pos2 == -1)
{
sb.Append(aSource.Substring(pos1));
break;
}
sb.Append(aSource.Substring(pos1, pos2 - pos1));
pos1 = pos2 + 1;
pos2 = pos1;
int end = Math.Min(len, pos2 + 10);
for (; pos2 < end; pos2++)
{
if (aSource[pos2] == ';')
break;
}
if (pos2 < end && pos2 > pos1)
{
string entity = aSource.Substring(pos1, pos2 - pos1);
int u = 0;
if (entity[0] == '#')
{
if (entity.Length > 1)
{
if (entity[1] == 'x')
u = Convert.ToInt16(entity.Substring(2), 16);
else
u = Convert.ToInt16(entity.Substring(1));
sb.Append((char)u);
pos1 = pos2 + 1;
}
else
sb.Append('&');
}
else
{
switch (entity)
{
case "amp":
u = 38;
break;
case "apos":
u = 39;
break;
case "gt":
u = 62;
break;
case "lt":
u = 60;
break;
case "nbsp":
u = 32;
break;
case "quot":
u = 34;
break;
}
if (u > 0)
{
sb.Append((char)u);
pos1 = pos2 + 1;
}
else
sb.Append('&');
}
}
else
{
sb.Append('&');
}
}
return sb.ToString();
}
private static string[] ESCAPES = new string[] {
"&", "&amp;",
"<", "&lt;",
">", "&gt;",
"'", "&apos;",
"\"", "&quot;",
"\t", "&#x9;",
"\n", "&#xA;",
"\r", "&#xD;"
};
public static void EncodeString(StringBuilder sb, int start, bool isAttribute = false)
{
int count;
int len = isAttribute ? ESCAPES.Length : 6;
for (int i = 0; i < len; i += 2)
{
count = sb.Length - start;
sb.Replace(ESCAPES[i], ESCAPES[i + 1], start, count);
}
}
public static string EncodeString(string str, bool isAttribute = false)
{
if (string.IsNullOrEmpty(str))
return "";
else
{
StringBuilder sb = new StringBuilder(str);
EncodeString(sb, 0);
return sb.ToString();
}
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 11312ca9745d52c4eb8e31630ad5ec7c
timeCreated: 1461773298
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -0,0 +1,114 @@
namespace FairyGUI.Utils
{
/// <summary>
/// 一个简单的Zip文件处理类。不处理解压。
/// </summary>
public class ZipReader
{
/// <summary>
///
/// </summary>
public class ZipEntry
{
public string name;
public int compress;
public uint crc;
public int size;
public int sourceSize;
public int offset;
public bool isDirectory;
}
ByteBuffer _stream;
int _entryCount;
int _pos;
int _index;
/// <summary>
///
/// </summary>
/// <param name="stream"></param>
public ZipReader(byte[] data)
{
_stream = new ByteBuffer(data);
_stream.littleEndian = true;
int pos = _stream.length - 22;
_stream.position = pos + 10;
_entryCount = _stream.ReadShort();
_stream.position = pos + 16;
_pos = _stream.ReadInt();
}
/// <summary>
///
/// </summary>
public int entryCount
{
get { return _entryCount; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool GetNextEntry(ZipEntry entry)
{
if (_index >= _entryCount)
return false;
_stream.position = _pos + 28;
int len = _stream.ReadUshort();
int len2 = _stream.ReadUshort() + _stream.ReadUshort();
_stream.position = _pos + 46;
string name = _stream.ReadString(len);
name = name.Replace("\\", "/");
entry.name = name;
if (name[name.Length - 1] == '/') //directory
{
entry.isDirectory = true;
entry.compress = 0;
entry.crc = 0;
entry.size = entry.sourceSize = 0;
entry.offset = 0;
}
else
{
entry.isDirectory = false;
_stream.position = _pos + 10;
entry.compress = _stream.ReadUshort();
_stream.position = _pos + 16;
entry.crc = _stream.ReadUint();
entry.size = _stream.ReadInt();
entry.sourceSize = _stream.ReadInt();
_stream.position = _pos + 42;
entry.offset = _stream.ReadInt() + 30 + len;
}
_pos += 46 + len + len2;
_index++;
return true;
}
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public byte[] GetEntryData(ZipEntry entry)
{
byte[] data = new byte[entry.size];
if (entry.size > 0)
{
_stream.position = entry.offset;
_stream.ReadBytes(data, 0, entry.size);
}
return data;
}
}
}

View File

@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: 8dc25ae9114bda14f998652db54f3af9
timeCreated: 1535374214
licenseType: Store
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: