Beispiel #1
0
        public static bool HasDefaultValue(this PropertyInfo property, object value)
        {
            var defaultAttribute = property.FindAttribute <DefaultValueAttribute>();

            object defaultAttributeValue = null;

            if (defaultAttribute != null)
            {
                defaultAttributeValue = defaultAttribute.Value;
                // If property is of Color type, than DefaultValueAttribute should contain its name or hex
                if (property.PropertyType == typeof(Color))
                {
                    defaultAttributeValue = ColorStorage.FromName(defaultAttributeValue.ToString()).Value;
                }

                if (property.PropertyType == typeof(string) &&
                    string.IsNullOrEmpty((string)defaultAttributeValue) &&
                    string.IsNullOrEmpty((string)value))
                {
                    // Skip empty/null string
                    return(true);
                }

                if (Equals(value, defaultAttributeValue))
                {
                    // Skip default
                    return(true);
                }
            }

            return(false);
        }
Beispiel #2
0
        private void TextBoxHexTextChangedByUser(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_textFieldHex.Text))
            {
                return;
            }

            var s = "#" + _textFieldHex.Text;

            var color = ColorStorage.FromName(s);

            if (color == null)
            {
                return;
            }

            try
            {
                _textFieldHex.Tag = true;
                Color             = color.Value;
            }
            finally
            {
                _textFieldHex.Tag = false;
            }
        }
Beispiel #3
0
        private void BuildUI()
        {
            var label1 = new Label();

            label1.Text                = "My Game";
            label1.Font                = AssetManager.Default.Load <SpriteFont>("fonts/arial64.fnt");
            label1.TextColor           = Color.LightBlue;
            label1.HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Center;

            _menuItemStartNewGame      = new MenuItem();
            _menuItemStartNewGame.Text = "Start New Game";
            _menuItemStartNewGame.Id   = "_menuItemStartNewGame";

            _menuItemOptions      = new MenuItem();
            _menuItemOptions.Text = "Options";
            _menuItemOptions.Id   = "_menuItemOptions";

            _menuItemQuit      = new MenuItem();
            _menuItemQuit.Text = "Quit";
            _menuItemQuit.Id   = "_menuItemQuit";

            _mainMenu = new VerticalMenu();
            _mainMenu.HorizontalAlignment      = Myra.Graphics2D.UI.HorizontalAlignment.Center;
            _mainMenu.VerticalAlignment        = Myra.Graphics2D.UI.VerticalAlignment.Center;
            _mainMenu.LabelFont                = AssetManager.Default.Load <SpriteFont>("fonts/comicSans48.fnt");
            _mainMenu.LabelColor               = Color.Indigo;
            _mainMenu.SelectionHoverBackground = new SolidBrush(ColorStorage.FromName("#808000FF").Value);
            _mainMenu.SelectionBackground      = new SolidBrush(ColorStorage.FromName("#FFA500FF").Value);
            _mainMenu.LabelHorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Center;
            _mainMenu.HoverIndexCanBeNull      = false;
            _mainMenu.Background               = new SolidBrush(ColorStorage.FromName("#00000000").Value);
            _mainMenu.Id = "_mainMenu";
            _mainMenu.Items.Add(_menuItemStartNewGame);
            _mainMenu.Items.Add(_menuItemOptions);
            _mainMenu.Items.Add(_menuItemQuit);

            var image1 = new Image();

            image1.Renderable        = AssetManager.Default.Load <TextureRegion>("images/LogoOnly_64px.png");
            image1.Left              = 10;
            image1.Top               = -10;
            image1.VerticalAlignment = Myra.Graphics2D.UI.VerticalAlignment.Bottom;

            var label2 = new Label();

            label2.Text = "Version 0.6";
            label2.Font = AssetManager.Default.Load <SpriteFont>("fonts/calibri32.fnt");
            label2.Left = -10;
            label2.Top  = -10;
            label2.HorizontalAlignment = Myra.Graphics2D.UI.HorizontalAlignment.Right;
            label2.VerticalAlignment   = Myra.Graphics2D.UI.VerticalAlignment.Bottom;


            Background = new SolidBrush(ColorStorage.FromName("#C78100FF").Value);
            Widgets.Add(label1);
            Widgets.Add(_mainMenu);
            Widgets.Add(image1);
            Widgets.Add(label2);
        }
Beispiel #4
0
        public SolidBrush(string color)
        {
            var c = ColorStorage.FromName(color);

            if (c == null)
            {
                throw new ArgumentException(string.Format("Could not recognize color '{0}'", color));
            }

            Color = c.Value;
        }
Beispiel #5
0
        public IBrush Load(AssetLoaderContext context, string assetName)
        {
            var color = ColorStorage.FromName(assetName);

            if (color == null)
            {
                throw new Exception(string.Format("Unable to resolve color '{0}'", assetName));
            }

            return(new SolidBrush(color.Value));
        }
Beispiel #6
0
        public static Stylesheet LoadFromSource(string stylesheetXml,
                                                Func <string, IBrush> textureGetter,
                                                Func <string, SpriteFont> fontGetter)
        {
            var xDoc = XDocument.Parse(stylesheetXml);

            var colors     = new Dictionary <string, Color>();
            var colorsNode = xDoc.Root.Element("Colors");

            if (colorsNode != null)
            {
                foreach (var el in colorsNode.Elements())
                {
                    var color = ColorStorage.FromName(el.Attribute("Value").Value);
                    if (color != null)
                    {
                        colors[el.Attribute(BaseContext.IdName).Value] = color.Value;
                    }
                }
            }

            Func <Type, string, object> resourceGetter = (t, s) =>
            {
                if (typeof(IBrush).IsAssignableFrom(t))
                {
                    return(textureGetter(s));
                }
                else if (t == typeof(SpriteFont))
                {
                    return(fontGetter(s));
                }

                throw new Exception(string.Format("Type {0} isn't supported", t.Name));
            };

            var result = new Stylesheet();

            var loadContext = new LoadContext
            {
                Namespaces = new[]
                {
                    typeof(WidgetStyle).Namespace
                },
                ResourceGetter      = resourceGetter,
                NodesToIgnore       = new HashSet <string>(new[] { "Designer", "Colors", "Fonts" }),
                LegacyClassNames    = LegacyClassNames,
                LegacyPropertyNames = LegacyPropertyNames,
                Colors = colors
            };

            loadContext.Load(result, xDoc.Root);

            return(result);
        }
Beispiel #7
0
        public static Color EnsureColor(this JObject obj, string fieldName)
        {
            var s      = obj.EnsureString(fieldName);
            var result = ColorStorage.FromName(s);

            if (result == null)
            {
                RaiseError("Could not find color '{0}'.", s);
            }

            return(result.Value);
        }
Beispiel #8
0
        private void HexInputChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_inputHEX.Text) || _inputHEX.Text.Length < 6)
            {
                return;
            }

            var color = ColorStorage.FromName('#' + _inputHEX.Text);

            if (color != null)
            {
                _inputHEX.Tag = true;
                var c = color.Value;
                OnColorChanged(new Color(c.R, c.G, c.B));
                _inputHEX.Tag = false;
            }
        }
Beispiel #9
0
        public Stylesheet Load(AssetLoaderContext context, string assetName)
        {
            var xml = context.Load <string>(assetName);

            var xDoc = XDocument.Parse(xml);
            var attr = xDoc.Root.Attribute("TextureRegionAtlas");

            if (attr == null)
            {
                throw new Exception("Mandatory attribute 'TextureRegionAtlas' doesnt exist");
            }

            var textureRegionAtlas = context.Load <TextureRegionAtlas>(attr.Value);

            // Load fonts
            var fonts     = new Dictionary <string, SpriteFont>();
            var fontsNode = xDoc.Root.Element("Fonts");

            foreach (var el in fontsNode.Elements())
            {
                var font = el.Attribute("File").Value;
                fonts[el.Attribute(BaseContext.IdName).Value] = context.Load <SpriteFont>(font);
            }

            return(Stylesheet.LoadFromSource(xml,
                                             name =>
            {
                TextureRegion region;

                if (!textureRegionAtlas.Regions.TryGetValue(name, out region))
                {
                    var color = ColorStorage.FromName(name);
                    if (color != null)
                    {
                        return new SolidBrush(color.Value);
                    }
                }
                else
                {
                    return region;
                }

                throw new Exception(string.Format("Could not find parse IBrush '{0}'", name));
            },
                                             name => fonts[name]));
        }
Beispiel #10
0
        public void Load(object obj, XElement el)
        {
            var type = obj.GetType();

            var baseObject = obj as BaseObject;

            List <PropertyInfo> complexProperties, simpleProperties;

            ParseProperties(type, out complexProperties, out simpleProperties);

            string newName;

            foreach (var attr in el.Attributes())
            {
                var propertyName = attr.Name.ToString();
                if (LegacyPropertyNames != null && LegacyPropertyNames.TryGetValue(propertyName, out newName))
                {
                    propertyName = newName;
                }

                var property = (from p in simpleProperties where p.Name == propertyName select p).FirstOrDefault();

                if (property != null)
                {
                    object value = null;

                    var propertyType = property.PropertyType;
                    if (propertyType.IsEnum)
                    {
                        value = Enum.Parse(propertyType, attr.Value);
                    }
                    else if (propertyType == typeof(Color) || propertyType == typeof(Color?))
                    {
                        Color color;
                        if (Colors != null && Colors.TryGetValue(attr.Value, out color))
                        {
                            value = color;
                        }
                        else
                        {
                            value = ColorStorage.FromName(attr.Value);
                            if (value == null)
                            {
                                throw new Exception(string.Format("Could not find parse color '{0}'", attr.Value));
                            }
                        }
                    }
                    else if ((typeof(IBrush).IsAssignableFrom(propertyType) ||
                              propertyType == typeof(SpriteFont)) &&
                             !string.IsNullOrEmpty(attr.Value) &&
                             ResourceGetter != null)
                    {
                        try
                        {
                            var texture = ResourceGetter(propertyType, attr.Value);
                            if (texture == null)
                            {
                                throw new Exception(string.Format("Could not find resource '{0}'", attr.Value));
                            }
                            value = texture;

                            if (baseObject != null)
                            {
                                baseObject.Resources[property.Name] = attr.Value;
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else if (propertyType == typeof(Thickness))
                    {
                        try
                        {
                            value = Thickness.FromString(attr.Value);
                        }
                        catch (Exception)
                        {
                        }
                    }
                    else
                    {
                        if (propertyType.IsNullablePrimitive())
                        {
                            propertyType = propertyType.GetNullableType();
                        }

                        value = Convert.ChangeType(attr.Value, propertyType, CultureInfo.InvariantCulture);
                    }

                    property.SetValue(obj, value);
                }
                else
                {
                    // Stow away custom user attributes
                    if (propertyName.StartsWith(UserDataAttributePrefix) && baseObject != null)
                    {
                        baseObject.UserData.Add(propertyName, attr.Value);
                    }
                }
            }

            var contentProperty = (from p in complexProperties
                                   where p.FindAttribute <ContentAttribute>()
                                   != null select p).FirstOrDefault();

            foreach (var child in el.Elements())
            {
                var childName = child.Name.ToString();
                if (NodesToIgnore != null && NodesToIgnore.Contains(childName))
                {
                    continue;
                }

                var isProperty = false;
                if (childName.Contains("."))
                {
                    // Property name
                    var parts = childName.Split('.');
                    childName  = parts[1];
                    isProperty = true;
                }

                if (LegacyPropertyNames != null && LegacyPropertyNames.TryGetValue(childName, out newName))
                {
                    childName = newName;
                }

                // Find property
                var property = (from p in complexProperties where p.Name == childName select p).FirstOrDefault();
                if (property != null)
                {
                    do
                    {
                        var value  = property.GetValue(obj);
                        var asList = value as IList;
                        if (asList != null)
                        {
                            // List
                            foreach (var child2 in child.Elements())
                            {
                                var item = ObjectCreator(property.PropertyType.GenericTypeArguments[0], child2);
                                Load(item, child2);
                                asList.Add(item);
                            }

                            break;
                        }

                        var asDict = value as IDictionary;
                        if (asDict != null)
                        {
                            // Dict
                            foreach (var child2 in child.Elements())
                            {
                                var item = ObjectCreator(property.PropertyType.GenericTypeArguments[1], child2);
                                Load(item, child2);

                                var id = string.Empty;
                                if (child2.Attribute(IdName) != null)
                                {
                                    id = child2.Attribute(IdName).Value;
                                }

                                asDict[id] = item;
                            }

                            break;
                        }

                        if (property.SetMethod == null)
                        {
                            // Readonly
                            Load(value, child);
                        }
                        else
                        {
                            var newValue = ObjectCreator(property.PropertyType, child);
                            Load(newValue, child);
                            property.SetValue(obj, newValue);
                        }
                        break;
                    } while (true);
                }
                else
                {
                    // Property not found
                    if (isProperty)
                    {
                        throw new Exception(string.Format("Class {0} doesnt have property {1}", type.Name, childName));
                    }

                    // Should be widget class name then
                    var widgetName = childName;
                    if (LegacyClassNames != null && LegacyClassNames.TryGetValue(widgetName, out newName))
                    {
                        widgetName = newName;
                    }

                    Type itemType = null;
                    foreach (var ns in Namespaces)
                    {
                        itemType = Assembly.GetType(ns + "." + widgetName);
                        if (itemType != null)
                        {
                            break;
                        }
                    }
                    if (itemType != null)
                    {
                        var item = ObjectCreator(itemType, child);
                        Load(item, child);

                        if (contentProperty == null)
                        {
                            throw new Exception(string.Format("Class {0} lacks property marked with ContentAttribute", type.Name));
                        }

                        var containerValue = contentProperty.GetValue(obj);
                        var asList         = containerValue as IList;
                        if (asList != null)
                        {
                            // List
                            asList.Add(item);
                        }
                        else
                        {
                            // Simple
                            contentProperty.SetValue(obj, item);
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("Could not resolve tag '{0}'", widgetName));
                    }
                }
            }
        }
Beispiel #11
0
        internal ChunkInfo LayoutRow(int startIndex, int?width, bool parseCommands)
        {
            var r = new ChunkInfo
            {
                StartIndex = startIndex,
                LineEnd    = true
            };

            if (string.IsNullOrEmpty(_text))
            {
                return(r);
            }

            _stringBuilder.Clear();
            int?  lastBreakPosition = null;
            Point?lastBreakMeasure  = null;

            for (var i = r.StartIndex; i < _text.Length; ++i)
            {
                var c = _text[i];

                if (SupportsCommands && c == '\\')
                {
                    if (i < _text.Length - 2 && _text[i + 1] == 'c' && _text[i + 2] == '[')
                    {
                        // Find end
                        var startPos = i + 3;
                        var j        = _text.IndexOf(']', startPos);

                        if (j != -1)
                        {
                            // Found
                            if (i > r.StartIndex)
                            {
                                // Break right here, as next chunk has another color
                                r.LineEnd = false;
                                return(r);
                            }

                            if (parseCommands)
                            {
                                r.Color = ColorStorage.FromName(_text.Substring(startPos, j - startPos));
                            }

                            r.StartIndex = j + 1;
                            i            = j;
                            continue;
                        }
                    }
                }

                _stringBuilder.Append(c);

                var sz = Point.Zero;

                if (c != '\n')
                {
                    var v = Font.MeasureString(_stringBuilder);
                    sz = new Point((int)v.X, (int)v.Y);
                }
                else
                {
                    sz = new Point(r.X + NewLineWidth, Math.Max(r.Y, CrossEngineStuff.LineSpacing(_font)));

                    // Break right here
                    ++r.CharsCount;
                    r.X = sz.X;
                    r.Y = sz.Y;
                    break;
                }

                if (width != null && sz.X > width.Value)
                {
                    if (lastBreakPosition != null)
                    {
                        r.CharsCount = lastBreakPosition.Value - r.StartIndex;
                    }

                    if (lastBreakMeasure != null)
                    {
                        r.X = lastBreakMeasure.Value.X;
                        r.Y = lastBreakMeasure.Value.Y;
                    }

                    break;
                }

                if (char.IsWhiteSpace(c))
                {
                    lastBreakPosition = i + 1;
                    lastBreakMeasure  = sz;
                }

                ++r.CharsCount;
                r.X = sz.X;
                r.Y = sz.Y;
            }

            return(r);
        }
Beispiel #12
0
        internal ChunkInfo LayoutRow(int startIndex, int?width, bool parseCommands)
        {
            var r = new ChunkInfo {
                StartIndex = startIndex, LineEnd = true
            };

            if (string.IsNullOrEmpty(_text))
            {
                return(r);
            }

            _stringBuilder.Clear();
            int?  lastBreakPosition = null;
            Point?lastBreakMeasure  = null;

            for (var i = r.StartIndex; i < _text.Length; ++i)
            {
                var c = _text[i];

                if (char.IsHighSurrogate(c))
                {
                    _stringBuilder.Append(c);
                    ++r.CharsCount;
                    continue;
                }

                if (SupportsCommands && c == '\\')
                {
                    if (i < _text.Length - 2)
                    {
                        char commandChar = _text[i + 1];

                        if (_text[i + 2] == '[')
                        {
                            // Find parameter end
                            var parameterStartIndex = i + 3;
                            var parameterEndIndex   = _text.IndexOf(']', parameterStartIndex);

                            if (parameterEndIndex != -1)
                            {
                                // Found
                                if (i > r.StartIndex)
                                {
                                    // Break right here, as next chunk is a command block
                                    if (commandChar == SpriteCommandChar)
                                    {
                                        // sprites have width, will this one fit on our line?
                                        if (width != null)
                                        {
                                            var spriteId = SpriteChunk.GetSpriteId(_text, parameterStartIndex, parameterEndIndex);
                                            var size     = TrollskogIntegration.MeasureSprite(spriteId, _font);
                                            r.LineEnd = (r.X + size.X) > width.Value;
                                        }
                                    }
                                    else
                                    {
                                        r.LineEnd = false;
                                    }

                                    return(r);
                                }

                                if (parseCommands && commandChar == ColorCommandChar)
                                {
                                    r.Color = ColorStorage.FromName(_text.Substring(parameterStartIndex, parameterEndIndex - parameterStartIndex));
                                }
                                else if (commandChar == SpriteCommandChar)
                                {
                                    // Break because this is a sprite chunk
                                    var spriteId = SpriteChunk.GetSpriteId(_text, parameterStartIndex, parameterEndIndex);
                                    var size     = TrollskogIntegration.MeasureSprite(spriteId, _font);

                                    r.LineEnd    = parameterEndIndex == _text.Length - 1;
                                    r.X          = size.X;
                                    r.Y          = size.Y;
                                    r.SpriteId   = spriteId;
                                    r.CharsCount = parameterEndIndex - r.StartIndex + 1;
                                    return(r);
                                }
                            }

                            r.StartIndex = parameterEndIndex + 1;
                            i            = parameterEndIndex;
                            continue;
                        }

                        if (commandChar == NewlineCommandChar)
                        {
                            Point sz2 = new(r.X + NewLineWidth, Math.Max(r.Y, _font.FontSize));

                            // Break right here, consuming 2 chars '\\' and 'n'
                            r.SkipChars   = 2;
                            r.CharsCount += 2;
                            r.LineEnd     = true;
                            r.X           = sz2.X;
                            r.Y           = sz2.Y;
                            break;
                        }
                    }
                }

                _stringBuilder.Append(c);

                Point sz;
                if (c != '\n')
                {
                    var v = Font.MeasureString(_stringBuilder);
                    sz = new Point((int)v.X, _font.FontSize);
                }
                else
                {
                    sz = new Point(r.X + NewLineWidth, Math.Max(r.Y, _font.FontSize));

                    // Break right here
                    ++r.CharsCount;
                    r.X = sz.X;
                    r.Y = sz.Y;
                    break;
                }

                if (width != null && sz.X > width.Value)
                {
                    if (lastBreakPosition != null)
                    {
                        r.CharsCount = lastBreakPosition.Value - r.StartIndex;
                    }

                    if (lastBreakMeasure != null)
                    {
                        r.X = lastBreakMeasure.Value.X;
                        r.Y = lastBreakMeasure.Value.Y;
                    }

                    break;
                }

                if (char.IsWhiteSpace(c))
                {
                    lastBreakPosition = i + 1;
                    lastBreakMeasure  = sz;
                }

                ++r.CharsCount;
                r.X = sz.X;
                r.Y = sz.Y;
            }

            return(r);
        }
Beispiel #13
0
        public static Stylesheet LoadFromSource(string stylesheetXml,
                                                TextureRegionAtlas textureRegionAtlas,
                                                Dictionary <string, SpriteFontBase> fonts)
        {
            var xDoc = XDocument.Parse(stylesheetXml);

            var colors     = new Dictionary <string, Color>();
            var colorsNode = xDoc.Root.Element("Colors");

            if (colorsNode != null)
            {
                foreach (var el in colorsNode.Elements())
                {
                    var color = ColorStorage.FromName(el.Attribute("Value").Value);
                    if (color != null)
                    {
                        colors[el.Attribute(BaseContext.IdName).Value] = color.Value;
                    }
                }
            }

            Func <Type, string, object> resourceGetter = (t, name) =>
            {
                if (typeof(IBrush).IsAssignableFrom(t))
                {
                    TextureRegion region;

                    if (!textureRegionAtlas.Regions.TryGetValue(name, out region))
                    {
                        var color = ColorStorage.FromName(name);
                        if (color != null)
                        {
                            return(new SolidBrush(color.Value));
                        }
                    }
                    else
                    {
                        return(region);
                    }

                    throw new Exception(string.Format("Could not find parse IBrush '{0}'", name));
                }
                else if (t == typeof(SpriteFontBase))
                {
                    return(fonts[name]);
                }

                throw new Exception(string.Format("Type {0} isn't supported", t.Name));
            };

            var result = new Stylesheet
            {
                Atlas = textureRegionAtlas,
                Fonts = fonts
            };

            var loadContext = new LoadContext
            {
                Namespaces = new[]
                {
                    typeof(WidgetStyle).Namespace
                },
                ResourceGetter      = resourceGetter,
                NodesToIgnore       = new HashSet <string>(new[] { "Designer", "Colors", "Fonts" }),
                LegacyClassNames    = LegacyClassNames,
                LegacyPropertyNames = LegacyPropertyNames,
                Colors = colors
            };

            loadContext.Load(result, xDoc.Root);

            return(result);
        }