public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException(nameof(destinationType));
            }

            if (value is SizeF size)
            {
                if (destinationType == typeof(string))
                {
                    if (culture == null)
                    {
                        culture = CultureInfo.CurrentCulture;
                    }

                    string        sep            = culture.TextInfo.ListSeparator + " ";
                    TypeConverter floatConverter = TypeDescriptor.GetConverter(typeof(float));
                    var           args           = new string[]
                    {
                        floatConverter.ConvertToString(context, culture, size.Width),
                        floatConverter.ConvertToString(context, culture, size.Height)
                    };
                    return(string.Join(sep, args));
                }
                else if (destinationType == typeof(InstanceDescriptor))
                {
                    ConstructorInfo ctor = typeof(SizeF).GetConstructor(new Type[] { typeof(float), typeof(float) });
                    if (ctor != null)
                    {
                        return(new InstanceDescriptor(ctor, new object[] { size.Width, size.Height }));
                    }
                }
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Exemple #2
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string strValue)
            {
                string text = strValue.Trim();
                if (text.Length == 0)
                {
                    return(null);
                }

                // Parse 2 integer values.
                if (culture == null)
                {
                    culture = CultureInfo.CurrentCulture;
                }

                char          sep          = culture.TextInfo.ListSeparator[0];
                string[]      tokens       = text.Split(sep);
                int[]         values       = new int[tokens.Length];
                TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
                for (int i = 0; i < values.Length; i++)
                {
                    // Note: ConvertFromString will raise exception if value cannot be converted.
                    values[i] = (int)intConverter.ConvertFromString(context, culture, tokens[i]);
                }

                if (values.Length != 2)
                {
                    throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, text, "Width,Height"));
                }

                return(new Size(values[0], values[1]));
            }

            return(base.ConvertFrom(context, culture, value));
        }
Exemple #3
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (!(value is string font))
            {
                return(base.ConvertFrom(context, culture, value));
            }

            font = font.Trim();

            // Expected string format: "name[, size[, units[, style=style1[, style2[...]]]]]"
            // Example using 'vi-VN' culture: "Microsoft Sans Serif, 8,25pt, style=Italic, Bold"
            if (font.Length == 0)
            {
                return(null);
            }

            if (culture == null)
            {
                culture = CultureInfo.CurrentCulture;
            }

            char         separator = culture.TextInfo.ListSeparator[0]; // For vi-VN: ','
            string       fontName  = font;                              // start with the assumption that only the font name was provided.
            string       style     = null;
            string       sizeStr   = null;
            float        fontSize  = 8.25f;
            FontStyle    fontStyle = FontStyle.Regular;
            GraphicsUnit units     = GraphicsUnit.Point;

            // Get the index of the first separator (would indicate the end of the name in the string).
            int nameIndex = font.IndexOf(separator);

            if (nameIndex < 0)
            {
                return(new Font(fontName, fontSize, fontStyle, units));
            }

            // Some parameters are provided in addition to name.
            fontName = font.Substring(0, nameIndex);

            if (nameIndex < font.Length - 1)
            {
                // Get the style index (if any). The size is a bit problematic because it can be formatted differently
                // depending on the culture, we'll parse it last.
                int styleIndex = culture.CompareInfo.IndexOf(font, StylePrefix, CompareOptions.IgnoreCase);

                if (styleIndex != -1)
                {
                    // style found.
                    style = font.Substring(styleIndex, font.Length - styleIndex);

                    // Get the mid-substring containing the size information.
                    sizeStr = font.Substring(nameIndex + 1, styleIndex - nameIndex - 1);
                }
                else
                {
                    // no style.
                    sizeStr = font.Substring(nameIndex + 1);
                }

                // Parse size.
                (string size, string unit)unitTokens = ParseSizeTokens(sizeStr, separator);

                if (unitTokens.size != null)
                {
                    try
                    {
                        fontSize = (float)TypeDescriptor.GetConverter(typeof(float)).ConvertFromString(context, culture, unitTokens.size);
                    }
                    catch
                    {
                        // Exception from converter is too generic.
                        throw new ArgumentException(SR.Format(SR.TextParseFailedFormat, font, $"name{separator} size[units[{separator} style=style1[{separator} style2{separator} ...]]]"), nameof(sizeStr));
                    }
                }

                if (unitTokens.unit != null)
                {
                    // ParseGraphicsUnits throws an ArgumentException if format is invalid.
                    units = ParseGraphicsUnits(unitTokens.unit);
                }

                if (style != null)
                {
                    // Parse FontStyle
                    style = style.Substring(6); // style string always starts with style=
                    string[] styleTokens = style.Split(separator);

                    for (int tokenCount = 0; tokenCount < styleTokens.Length; tokenCount++)
                    {
                        string styleText = styleTokens[tokenCount];
                        styleText = styleText.Trim();

                        fontStyle |= (FontStyle)Enum.Parse(typeof(FontStyle), styleText, true);

                        // Enum.IsDefined doesn't do what we want on flags enums...
                        FontStyle validBits = FontStyle.Regular | FontStyle.Bold | FontStyle.Italic | FontStyle.Underline | FontStyle.Strikeout;
                        if ((fontStyle | validBits) != validBits)
                        {
                            throw new InvalidEnumArgumentException(nameof(style), (int)fontStyle, typeof(FontStyle));
                        }
                    }
                }
            }

            return(new Font(fontName, fontSize, fontStyle, units));
        }
Exemple #4
0
 static TypeConverter GetFloatConverter() => TypeDescriptor.GetConverter(typeof(float));
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            FontStyle    f_style;
            float        f_size;
            GraphicsUnit f_unit;
            string       font;
            string       units;

            string[] fields;

            if (!(value is string))
            {
                return(base.ConvertFrom(context, culture, value));
            }

            font = (string)value;
            font = font.Trim();

            if (font.Length == 0)
            {
                return(null);
            }

            if (culture == null)
            {
                culture = CultureInfo.CurrentCulture;
            }

            // Format is FontFamily, size[<units>[, style=1,2,3]]
            // This is a bit tricky since the comma can be used for styles and fields
            fields = font.Split(new char[] { culture.TextInfo.ListSeparator[0] });
            if (fields.Length < 1)
            {
                throw new ArgumentException("Failed to parse font format");
            }

            font   = fields[0];
            f_size = 8f;
            units  = "px";
            f_unit = GraphicsUnit.Pixel;
            if (fields.Length > 1)      // We have a size
            {
                for (int i = 0; i < fields[1].Length; i++)
                {
                    if (Char.IsLetter(fields[1][i]))
                    {
                        f_size = (float)TypeDescriptor.GetConverter(typeof(float)).ConvertFromString(context, culture, fields[1].Substring(0, i));
                        units  = fields[1].Substring(i);
                        break;
                    }
                }
                if (units == "display")
                {
                    f_unit = GraphicsUnit.Display;
                }
                else if (units == "doc")
                {
                    f_unit = GraphicsUnit.Document;
                }
                else if (units == "pt")
                {
                    f_unit = GraphicsUnit.Point;
                }
                else if (units == "in")
                {
                    f_unit = GraphicsUnit.Inch;
                }
                else if (units == "mm")
                {
                    f_unit = GraphicsUnit.Millimeter;
                }
                else if (units == "px")
                {
                    f_unit = GraphicsUnit.Pixel;
                }
                else if (units == "world")
                {
                    f_unit = GraphicsUnit.World;
                }
            }

            f_style = FontStyle.Regular;
            if (fields.Length > 2)      // We have style
            {
                string compare;

                for (int i = 2; i < fields.Length; i++)
                {
                    compare = fields[i];

                    if (compare.IndexOf("Regular") != -1)
                    {
                        f_style |= FontStyle.Regular;
                    }
                    if (compare.IndexOf("Bold") != -1)
                    {
                        f_style |= FontStyle.Bold;
                    }
                    if (compare.IndexOf("Italic") != -1)
                    {
                        f_style |= FontStyle.Italic;
                    }
                    if (compare.IndexOf("Strikeout") != -1)
                    {
                        f_style |= FontStyle.Strikeout;
                    }
                    if (compare.IndexOf("Underline") != -1)
                    {
                        f_style |= FontStyle.Underline;
                    }
                }
            }

            return(new Font(font, f_size, f_style, f_unit));
        }
Exemple #6
0
        /// <include file='doc\ColorConverter.uex' path='docs/doc[@for="ColorConverter.ConvertTo"]/*' />
        /// <devdoc>
        ///      Converts the given object to another type.  The most common types to convert
        ///      are to and from a string object.  The default implementation will make a call
        ///      to ToString on the object if the object is valid and if the destination
        ///      type is string.  If this cannot convert to the desitnation type, this will
        ///      throw a NotSupportedException.
        /// </devdoc>
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (destinationType == null)
            {
                throw new ArgumentNullException(nameof(destinationType));
            }

            if (value is Color)
            {
                if (destinationType == typeof(string))
                {
                    Color c = (Color)value;

                    if (c == Color.Empty)
                    {
                        return(string.Empty);
                    }
                    else
                    {
                        // If this is a known color, then Color can provide its own
                        // name.  Otherwise, we fabricate an ARGB value for it.
                        //
                        if (c.IsKnownColor)
                        {
                            return(c.Name);
                        }
                        else if (c.IsNamedColor)
                        {
                            return("'" + c.Name + "'");
                        }
                        else
                        {
                            if (culture == null)
                            {
                                culture = CultureInfo.CurrentCulture;
                            }
                            string        sep          = culture.TextInfo.ListSeparator + " ";
                            TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));
                            string[]      args;
                            int           nArg = 0;

                            if (c.A < 255)
                            {
                                args         = new string[4];
                                args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.A);
                            }
                            else
                            {
                                args = new string[3];
                            }

                            // Note: ConvertToString will raise exception if value cannot be converted.
                            args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.R);
                            args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.G);
                            args[nArg++] = intConverter.ConvertToString(context, culture, (object)c.B);

                            // Now slam all of these together with the fantastic Join
                            // method.
                            //
                            return(string.Join(sep, args));
                        }
                    }
                }
                if (destinationType == typeof(InstanceDescriptor))
                {
                    MemberInfo member = null;
                    object[]   args   = null;

                    Color c = (Color)value;

                    if (c.IsEmpty)
                    {
                        member = typeof(Color).GetField("Empty");
                    }
                    else if (c.IsSystemColor)
                    {
                        member = typeof(SystemColors).GetProperty(c.Name);
                    }
                    else if (c.IsKnownColor)
                    {
                        member = typeof(Color).GetProperty(c.Name);
                    }
                    else if (c.A != 255)
                    {
                        member = typeof(Color).GetMethod("FromArgb", new Type[] { typeof(int), typeof(int), typeof(int), typeof(int) });
                        args   = new object[] { c.A, c.R, c.G, c.B };
                    }
                    else if (c.IsNamedColor)
                    {
                        member = typeof(Color).GetMethod("FromName", new Type[] { typeof(string) });
                        args   = new object[] { c.Name };
                    }
                    else
                    {
                        member = typeof(Color).GetMethod("FromArgb", new Type[] { typeof(int), typeof(int), typeof(int) });
                        args   = new object[] { c.R, c.G, c.B };
                    }

                    Debug.Assert(member != null, "Could not convert color to member.  Did someone change method name / signature and not update Colorconverter?");
                    if (member != null)
                    {
                        return(new InstanceDescriptor(member, args));
                    }
                    else
                    {
                        return(null);
                    }
                }
            }

            return(base.ConvertTo(context, culture, value, destinationType));
        }
Exemple #7
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            string strValue = value as string;

            if (strValue != null)
            {
                object obj  = null;
                string text = strValue.Trim();

                if (text.Length == 0)
                {
                    obj = Color.Empty;
                }
                else
                {
                    // First, check to see if this is a standard name.
                    //
                    obj = GetNamedColor(text);

                    if (obj == null)
                    {
                        if (culture == null)
                        {
                            culture = CultureInfo.CurrentCulture;
                        }

                        char sep = culture.TextInfo.ListSeparator[0];
                        bool tryMappingToKnownColor = true;

                        TypeConverter intConverter = TypeDescriptor.GetConverter(typeof(int));

                        // If the value is a 6 digit hex number only, then
                        // we want to treat the Alpha as 255, not 0
                        //
                        if (text.IndexOf(sep) == -1)
                        {
                            // text can be '' (empty quoted string)
                            if (text.Length >= 2 && (text[0] == '\'' || text[0] == '"') && text[0] == text[text.Length - 1])
                            {
                                // In quotes means a named value
                                string colorName = text.Substring(1, text.Length - 2);
                                obj = Color.FromName(colorName);
                                tryMappingToKnownColor = false;
                            }
                            else if ((text.Length == 7 && text[0] == '#') ||
                                     (text.Length == 8 && (text.StartsWith("0x") || text.StartsWith("0X"))) ||
                                     (text.Length == 8 && (text.StartsWith("&h") || text.StartsWith("&H"))))
                            {
                                // Note: ConvertFromString will raise exception if value cannot be converted.
                                obj = Color.FromArgb(unchecked ((int)(0xFF000000 | (uint)(int)intConverter.ConvertFromString(context, culture, text))));
                            }
                        }

                        // Nope.  Parse the RGBA from the text.
                        //
                        if (obj == null)
                        {
                            string[] tokens = text.Split(new char[] { sep });
                            int[]    values = new int[tokens.Length];
                            for (int i = 0; i < values.Length; i++)
                            {
                                values[i] = unchecked ((int)intConverter.ConvertFromString(context, culture, tokens[i]));
                            }

                            // We should now have a number of parsed integer values.
                            // We support 1, 3, or 4 arguments:
                            //
                            // 1 -- full ARGB encoded
                            // 3 -- RGB
                            // 4 -- ARGB
                            //
                            switch (values.Length)
                            {
                            case 1:
                                obj = Color.FromArgb(values[0]);
                                break;

                            case 3:
                                obj = Color.FromArgb(values[0], values[1], values[2]);
                                break;

                            case 4:
                                obj = Color.FromArgb(values[0], values[1], values[2], values[3]);
                                break;
                            }
                            tryMappingToKnownColor = true;
                        }

                        if ((obj != null) && tryMappingToKnownColor)
                        {
                            // Now check to see if this color matches one of our known colors.
                            // If it does, then substitute it.  We can only do this for "Colors"
                            // because system colors morph with user settings.
                            //
                            int targetARGB = ((Color)obj).ToArgb();

                            foreach (Color c in Colors.Values)
                            {
                                if (c.ToArgb() == targetARGB)
                                {
                                    obj = c;
                                    break;
                                }
                            }
                        }
                    }

                    if (obj == null)
                    {
                        throw new ArgumentException(SR.Format(SR.InvalidColor, text));
                    }
                }
                return(obj);
            }
            return(base.ConvertFrom(context, culture, value));
        }