Ejemplo n.º 1
0
 /// <summary>
 /// Attempts to convert color string in Hexadecimal or HDR color format to the
 /// corresponding Color object.
 /// The hexadecimal color string should be in #RRGGBB or #AARRGGBB format.
 /// The '#' character is optional.
 /// The HDR color string should be in R G B A format.
 /// (R, G, B &amp; A should have value in the range between 0 and 1, inclusive)
 /// </summary>
 /// <param name="colorString">Color string in Hexadecimal or HDR format</param>
 /// <param name="color">Output Color object</param>
 /// <returns>True if successful, otherwise False</returns>
 public static bool TryCreateColor(string colorString, out Color color)
 {
     using (new CultureShield("en-US"))
     {
         return(ColorParser.TryParse(colorString, out color));
     }
 }
Ejemplo n.º 2
0
    public override ValidationResult Validate(object value, CultureInfo cultureInfo)
    {
        if (value is not string hexString)
        {
            return(new ValidationResult(false, "Input is null"));
        }

        if (ColorParser.TryParse(hexString, Wrapper.ColorModel, out _))
        {
            return(ValidationResult.ValidResult);
        }

        return(new ValidationResult(false, "Color is invalid"));
    }
Ejemplo n.º 3
0
    public Palette ToPalette(IColorFactory colorFactory)
    {
        var pal = new Palette(Name, colorFactory, ColorModel.Rgba32, ZeroIndexTransparent, PaletteStorageSource.Json);

        var colors = new List <IColorSource>();

        for (int i = 0; i < Colors.Count; i++)
        {
            if (ColorParser.TryParse(Colors[i], ColorModel.Rgba32, out var color))
            {
                colors.Add(new ProjectNativeColorSource((ColorRgba32)color));
            }
        }

        pal.SetColorSources(colors);

        return(pal);
    }
Ejemplo n.º 4
0
        public Vector2I UpdateVertexArray(string text, ref VertexDefinition.PositionTextureColor[] vertices, ref Buffer vertexBuffer, Color defaultColor, List <TexturedRectangle> icons, int positionX = 0, int positionY = 0)
        {
            icons.Clear();
            Color color     = defaultColor;
            int   width     = 0;
            int   maxWidth  = 0;
            int   height    = Characters.First().Value.height;
            int   maxHeight = height;

            for (int i = 0; i < text.Length; i++)
            {
                char letter = text[i];
                if (letter == '\n')
                {
                    maxWidth   = Math.Max(maxWidth, width);
                    width      = 0;
                    positionX  = 0;
                    positionY += height;
                    maxHeight += height;
                    continue;
                }
                if (letter == '[')
                {
                    if (text[i + 1] == '[')
                    {
                        continue;
                    }
                    string token = text.Substring(i + 1, text.IndexOf(']', i + 1) - (i + 1));
                    if (!ColorParser.TryParse(token, out color))
                    {
                        if (token == "-")
                        {
                            color = defaultColor;
                        }
                        else if (token == "gold")
                        {
                            icons.Add(new TexturedRectangle(_context,
                                                            _context.TextureManager.Create("gold.png", "Data/UI/Icons/"), new Vector2I(height, height)));
                            positionX += height + 1;
                            width     += height + 1;
                        }
                        else
                        {
                            throw new InvalidOperationException("Unexpected token : " + token);
                        }
                    }
                    i = text.IndexOf(']', i + 1);
                    continue;
                }
                Character c             = Characters[letter];
                Vector4   colorAsVector = color.ToVector4();
                vertices[i * 4] = new VertexDefinition.PositionTextureColor {
                    position = new Vector3(positionX, positionY, 0.0f), texture = new Vector2(c.uLeft, c.vTop), color = colorAsVector
                };                                                                                                                                                                                 //Top left
                vertices[i * 4 + 1] = new VertexDefinition.PositionTextureColor {
                    position = new Vector3(positionX + c.width, positionY + c.height, 0.0f), texture = new Vector2(c.uRight, c.vBottom), color = colorAsVector
                };                                                                                                                                                                                                              //Right bottom
                vertices[i * 4 + 2] = new VertexDefinition.PositionTextureColor {
                    position = new Vector3(positionX, positionY + c.height, 0.0f), texture = new Vector2(c.uLeft, c.vBottom), color = colorAsVector
                };                                                                                                                                                                                                   //Left bottom
                vertices[i * 4 + 3] = new VertexDefinition.PositionTextureColor {
                    position = new Vector3(positionX + c.width, positionY, 0.0f), texture = new Vector2(c.uRight, c.vTop), color = colorAsVector
                };                                                                                                                                                                                                //Top right

                positionX += c.width + 1;
                width     += c.width + 1;
            }
            DataStream mappedResource;

            _context.DirectX.Device.ImmediateContext.MapSubresource(vertexBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None,
                                                                    out mappedResource);
            mappedResource.WriteRange(vertices);
            _context.DirectX.Device.ImmediateContext.UnmapSubresource(vertexBuffer, 0);
            return(new Vector2I(Math.Max(maxWidth, width), maxHeight));
        }
Ejemplo n.º 5
0
    private bool TryDeserializePalette(XElement element, string resourceName, out PaletteModel paletteModel)
    {
        var model = new PaletteModel();

        model.Name                 = resourceName;
        model.DataFileKey          = element.Attribute("datafile").Value;
        model.ColorModel           = Palette.StringToColorModel(element.Attribute("color").Value);
        model.ZeroIndexTransparent = bool.Parse(element.Attribute("zeroindextransparent").Value);

        foreach (var item in element.Elements())
        {
            if (item.Name.LocalName == "filesource")
            {
                var source     = new FileColorSourceModel();
                var fileOffset = long.Parse(item.Attribute("fileoffset").Value, System.Globalization.NumberStyles.HexNumber);
                if (item.Attribute("bitoffset") is null)
                {
                    source.FileAddress = new BitAddress(fileOffset, 0);
                }
                else
                {
                    source.FileAddress = new BitAddress(fileOffset, int.Parse(element.Attribute("bitoffset").Value));
                }

                source.Entries = int.Parse(item.Attribute("entries").Value);

                if (item.Attribute("endian") is not null)
                {
                    if (item.Attribute("endian").Value == "big")
                    {
                        source.Endian = Endian.Big;
                    }
                    else if (item.Attribute("endian").Value == "little")
                    {
                        source.Endian = Endian.Little;
                    }
                    else
                    {
                        _errors.Add($"'endian' has unknown value '{item.Attribute("endian").Value}'");
                    }
                }

                model.ColorSources.Add(source);
            }
            else if (item.Name.LocalName == "nativecolor")
            {
                if (ColorParser.TryParse(item.Attribute("value").Value, ColorModel.Rgba32, out var nativeColor))
                {
                    model.ColorSources.Add(new ProjectNativeColorSourceModel((ColorRgba32)nativeColor));
                }
            }
            else if (item.Name.LocalName == "foreigncolor")
            {
                if (ColorParser.TryParse(item.Attribute("value").Value, model.ColorModel, out var foreignColor))
                {
                    model.ColorSources.Add(new ProjectForeignColorSourceModel(foreignColor));
                }
            }
            else if (item.Name.LocalName == "scatteredcolor")
            {
            }
            else if (item.Name.LocalName == "import")
            {
            }
            else if (item.Name.LocalName == "export")
            {
            }
        }

        paletteModel = model;
        return(true);
    }
Ejemplo n.º 6
0
        private void CreateVertexBuffer(Device device)
        {
            _vertices = new VertexDefinition.PositionTextureColor[_numberOfLetters * 4];
            int   letterIndex = 0;
            Color color       = BaseColor;
            int   lineHeight  = Font.Characters.First().Value.height;
            float spaceSize   = SpaceSize;

            float positionY = Padding.Top;

            if (VerticalAlignment == VerticalAlignment.Bottom)
            {
                positionY = Size.Y - (lineHeight * Lines.Count + LineSpacing * (Lines.Count - 1)) - Padding.Bottom;
            }
            if (VerticalAlignment == VerticalAlignment.Middle)
            {
                positionY = Padding.Top + (float)(Size.Y - Padding.Bottom - Padding.Top - (lineHeight * Lines.Count + LineSpacing * (Lines.Count - 1))) / 2;
            }

            for (int i = 0; i < Lines.Count; i++)
            {
                TextLine line = Lines[i];
                line.Width -= SpaceSize + 1; //Remove last space and pixel padding after last character
                float positionX = Padding.Left;
                if (HorizontalAlignment == HorizontalAlignment.Right)
                {
                    positionX = Size.X - line.Width - Padding.Right;
                }
                if (HorizontalAlignment == HorizontalAlignment.Center)
                {
                    positionX = Padding.Left + (float)(Size.X - Padding.Left - Padding.Right - line.Width) / 2;
                }
                if (HorizontalAlignment == HorizontalAlignment.Justify && line.WordWrapped)
                {
                    spaceSize = SpaceSize + (float)(Size.X - Padding.Left - Padding.Right - line.Width) / (line.WordCount - 1);
                }
                for (int j = 0; j < line.Words.Count; j++)
                {
                    string word = line.Words[j];
                    for (int k = 0; k < word.Length; k++)
                    {
                        char letter = word[k];
                        if (letter == '[')
                        {
                            if (word[k + 1] != '[')
                            {
                                string token = word.Substring(k + 1, word.IndexOf(']', k + 1) - (k + 1));
                                if (token == "-")
                                {
                                    color = BaseColor;
                                }
                                else if (!ColorParser.TryParse(token, out color))
                                {
                                    throw new InvalidOperationException("Unexpected token : " + token);
                                }
                                k = word.IndexOf(']', k + 1);
                                continue;
                            }
                            k++;
                        }
                        Vector4        colorAsVector = color.ToVector4();
                        Font.Character c             = Font.Characters[letter];
                        _vertices[letterIndex * 4] = new VertexDefinition.PositionTextureColor {
                            position = new Vector3(positionX, positionY, 0.0f), texture = new Vector2(c.uLeft, c.vTop), color = colorAsVector
                        };                                                                                                                                                                                            //Top left
                        _vertices[letterIndex * 4 + 1] = new VertexDefinition.PositionTextureColor {
                            position = new Vector3(positionX + c.width, positionY + c.height, 0.0f), texture = new Vector2(c.uRight, c.vBottom), color = colorAsVector
                        };                                                                                                                                                                                                                         //Right bottom
                        _vertices[letterIndex * 4 + 2] = new VertexDefinition.PositionTextureColor {
                            position = new Vector3(positionX, positionY + c.height, 0.0f), texture = new Vector2(c.uLeft, c.vBottom), color = colorAsVector
                        };                                                                                                                                                                                                              //Left bottom
                        _vertices[letterIndex * 4 + 3] = new VertexDefinition.PositionTextureColor {
                            position = new Vector3(positionX + c.width, positionY, 0.0f), texture = new Vector2(c.uRight, c.vTop), color = colorAsVector
                        };                                                                                                                                                                                                           //Top right
                        positionX += c.width + 1;
                        letterIndex++;
                    }
                    positionX += spaceSize;
                }
                positionY += lineHeight + LineSpacing;
            }
            if (_vertexBuffer != null)
            {
                _vertexBuffer.Dispose();
            }
            _vertexBuffer = Buffer.Create(device, BindFlags.VertexBuffer, _vertices);
            UsedSize      = new Vector2I(Lines.Max(l => l.Width) + Padding.Left + Padding.Right,
                                         (lineHeight * Lines.Count + LineSpacing * (Lines.Count - 1)) + Padding.Bottom + Padding.Top);
        }
Ejemplo n.º 7
0
        private ClipboardViewModel CreateClipboardViewModel(ClipboardState state)
        {
            ClipboardItem item = ClipboardParser.GetPreferredItem(state.Items, serializable: false);

            if (item == null)
            {
                _logger.LogInfo(LogEvents.UnknClipbdFmt, state.Items.Select(x => new { x.Format, x.FormatName }));
                return(new UnknownViewModel(
                           state,
                           DateTime.Now,
                           onPaste: OnPasteStateClicked,
                           onDelete: OnDeleteStateClicked));
            }

            switch (ClipboardParser.GetAbstractFormat(item.Format))
            {
            case AbstractDataFormat.Image:
                return(new ImageViewModel(
                           state,
                           DateTime.Now,
                           onPaste: OnPasteStateClicked,
                           onDelete: OnDeleteStateClicked)
                {
                    Image = ClipboardParser.ParseImage(item),
                });

            case AbstractDataFormat.Text:
                var    text   = ClipboardParser.ParseText(item);
                string source = text.Trim();
                if (source.Length < 50 && ColorParser.TryParse(source, out Color color))
                {
                    Color textColor = (color.R + color.G + color.B) * (float)color.A / 255 / 3 >= 127
                            ? System.Windows.Media.Colors.Black
                            : System.Windows.Media.Colors.White;
                    return(new ColorViewModel(
                               state,
                               DateTime.Now,
                               onPaste: OnPasteStateClicked,
                               onDelete: OnDeleteStateClicked)
                    {
                        BackgroundColor = new SolidColorBrush(color),
                        TextColor = new SolidColorBrush(textColor),
                        Text = text.Trim(),
                    });
                }
                else
                {
                    string textContent = PostProcessText(ClipboardParser.ParseText(item));
                    return(new TextViewModel(
                               state,
                               DateTime.Now,
                               onPaste: OnPasteStateClicked,
                               onDelete: OnDeleteStateClicked)
                    {
                        Text = textContent,
                    });
                }

            case AbstractDataFormat.FileDrop:
                string[] items = ClipboardParser.ParseFileDrop(item)
                                 .Where(x => File.Exists(x) || Directory.Exists(x))
                                 .ToArray();
                return(new FileDropViewModel(
                           state,
                           DateTime.Now,
                           onPaste: OnPasteStateClicked,
                           onDelete: OnDeleteStateClicked)
                {
                    Items = items,
                });

            default:
                _logger.LogInfo(LogEvents.UnknClipbdFmt, state.Items.Select(x => new { x.Format, x.FormatName }));
                return(new UnknownViewModel(
                           state,
                           DateTime.Now,
                           onPaste: OnPasteStateClicked,
                           onDelete: OnDeleteStateClicked));
            }
        }
 /// <summary>
 /// Attempts to convert color string in Hexadecimal or HDR color format to the
 /// corresponding Color object.
 /// The hexadecimal color string should be in #RRGGBB or #AARRGGBB format.
 /// The '#' character is optional.
 /// The HDR color string should be in R G B A format.
 /// (R, G, B & A should have value in the range between 0 and 1, inclusive)
 /// </summary>
 /// <param name="colorString">Color string in Hexadecimal or HDR format</param>
 /// <param name="color">Output Color object</param>
 /// <returns>True if successful, otherwise False</returns>
 public static bool TryCreateColor(string colorString, out Color color)
 {
     return(ColorParser.TryParse(colorString, out color));
 }