Beispiel #1
0
        public void EvaluateFormat(object current, Core.Parsing.Format format, ref bool handled, IOutput output, FormatDetails formatDetails)
        {
            // Ignore formats that start with "?" (this can be used to bypass this extension)
            if (format == null || format.baseString[format.startIndex] == ':')
            {
                return;
            }

            // Extract the plural words from the format string:
            var pluralWords = format.Split("|");

            // This extension requires at least two plural words:
            if (pluralWords.Count == 1)
            {
                return;
            }

            // See if the value is a number:
            var currentIsNumber =
                current is byte || current is short || current is int || current is long ||
                current is float || current is double || current is decimal;

            // This extension only formats numbers:
            if (!currentIsNumber)
            {
                return;
            }

            // Normalize the number to decimal:
            var value = Convert.ToDecimal(current);

            // Get the plural rule:
            var provider   = formatDetails.Provider;
            var pluralRule = GetPluralRule(provider);

            if (pluralRule == null)
            {
                // Not a supported language.
                return;
            }

            var pluralCount = pluralWords.Count;
            var pluralIndex = pluralRule(value, pluralCount);

            if (pluralIndex < 0 || pluralWords.Count <= pluralIndex)
            {
                // The plural rule should always return a value in-range!
                throw new FormatException(format, "Invalid number of plural parameters", pluralWords.Last().endIndex);
            }

            // Output the selected word (allowing for nested formats):
            var pluralForm = pluralWords[pluralIndex];

            formatDetails.Formatter.Format(output, pluralForm, current, formatDetails);
            handled = true;
        }
Beispiel #2
0
        /// <summary>
        /// If the source value is an array (or supports ICollection),
        /// then each item will be custom formatted.
        ///
        ///
        /// Syntax:
        /// #1: "format|spacer"
        /// #2: "format|spacer|last spacer"
        /// #3: "format|spacer|last spacer|two spacer"
        ///
        /// The format will be used for each item in the collection, the spacer will be between all items, and the last spacer will replace the spacer for the last item only.
        ///
        /// Example:
        /// CustomFormat("{Dates:D|; |; and }", {#1/1/2000#, #12/31/2999#, #9/9/9999#}) = "January 1, 2000; December 31, 2999; and September 9, 9999"
        /// In this example, format = "D", spacer = "; ", and last spacer = "; and "
        ///
        ///
        ///
        /// Advanced:
        /// Composite Formatting is allowed in the format by using nested braces.
        /// If a nested item is detected, Composite formatting will be used.
        ///
        /// Example:
        /// CustomFormat("{Sizes:{Width}x{Height}|, }", {new Size(4,3), new Size(16,9)}) = "4x3, 16x9"
        /// In this example, format = "{Width}x{Height}".  Notice the nested braces.
        ///
        /// </summary>
        public void EvaluateFormat(object current, Core.Parsing.Format format, ref bool handled, IOutput output, FormatDetails formatDetails)
        {
            // This method needs the Highest priority so that it comes before the PluralLocalizationExtension and ConditionalExtension

            // This extension requires at least IEnumerable
            var enumerable = current as IEnumerable;

            if (enumerable == null)
            {
                return;
            }
            // Ignore Strings, because they're IEnumerable.
            // This issue might actually need a solution
            // for other objects that are IEnumerable.
            if (current is string)
            {
                return;
            }
            // If the object is IFormattable, ignore it
            if (current is IFormattable)
            {
                return;
            }

            // This extension requires a | to specify the spacer:
            if (format == null)
            {
                return;
            }
            var parameters = format.Split("|", 4);

            if (parameters.Count < 2)
            {
                return;
            }

            // Grab all formatting options:
            // They must be in one of these formats:
            // itemFormat|spacer
            // itemFormat|spacer|lastSpacer
            // itemFormat|spacer|lastSpacer|twoSpacer
            var itemFormat = parameters[0];
            var spacer     = (parameters.Count >= 2) ? parameters[1].Text : "";
            var lastSpacer = (parameters.Count >= 3) ? parameters[2].Text : spacer;
            var twoSpacer  = (parameters.Count >= 4) ? parameters[3].Text : lastSpacer;

            if (!itemFormat.HasNested)
            {
                // The format is not nested,
                // so we will treat it as an itemFormat:
                var newItemFormat = new Core.Parsing.Format(itemFormat.baseString);
                newItemFormat.startIndex = itemFormat.startIndex;
                newItemFormat.endIndex   = itemFormat.endIndex;
                newItemFormat.HasNested  = true;
                var newPlaceholder = new Placeholder(newItemFormat, itemFormat.startIndex, formatDetails.Placeholder.NestedDepth);
                newPlaceholder.Format   = itemFormat;
                newPlaceholder.endIndex = itemFormat.endIndex;
                newItemFormat.Items.Add(newPlaceholder);
                itemFormat = newItemFormat;
            }

            // Let's buffer all items from the enumerable (to ensure the Count without double-enumeration):
            ICollection items = current as ICollection;

            if (items == null)
            {
                var allItems = new List <object>();
                foreach (var item in enumerable)
                {
                    allItems.Add(item);
                }
                items = allItems;
            }

            int oldCollectionIndex = CollectionIndex; // In case we have nested arrays, we might need to restore the CollectionIndex

            CollectionIndex = -1;
            foreach (object item in items)
            {
                CollectionIndex += 1; // Keep track of the index

                // Determine which spacer to write:
                if (spacer == null || CollectionIndex == 0)
                {
                    // Don't write the spacer.
                }
                else if (CollectionIndex < items.Count - 1)
                {
                    output.Write(spacer, formatDetails);
                }
                else if (CollectionIndex == 1)
                {
                    output.Write(twoSpacer, formatDetails);
                }
                else
                {
                    output.Write(lastSpacer, formatDetails);
                }

                // Output the nested format for this item:
                formatDetails.Formatter.Format(output, itemFormat, item, formatDetails);
            }

            CollectionIndex = oldCollectionIndex; // Restore the CollectionIndex

            handled = true;
        }
Beispiel #3
0
        public void EvaluateFormat(object current, Core.Parsing.Format format, ref bool handled, IOutput output, FormatDetails formatDetails)
        {
            if (format == null)
            {
                return;
            }
            // Ignore a leading ":", which is used to bypass the PluralLocalizationExtension
            if (format.baseString[format.startIndex] == ':')
            {
                format = format.Substring(1);
            }

            // See if the format string contains un-nested "|":
            var parameters = format.Split("|");

            if (parameters.Count == 1)
            {
                return;                        // There are no parameters found.
            }
            // See if the value is a number:
            var currentIsNumber =
                current is byte || current is short || current is int || current is long ||
                current is float || current is double || current is decimal;

            // An Enum is a number too:
            if (currentIsNumber == false && current != null && current.GetType().IsEnum)
            {
                currentIsNumber = true;
            }
            var currentNumber = currentIsNumber ? Convert.ToDecimal(current) : 0;


            int paramIndex; // Determines which parameter to use for output

            // First, we'll see if we are using "complex conditions":
            if (currentIsNumber)
            {
                paramIndex = -1;
                while (true)
                {
                    paramIndex++;
                    if (paramIndex == parameters.Count)
                    {
                        // We reached the end of our parameters,
                        // so we output nothing
                        handled = true;
                        return;
                    }
                    bool conditionWasTrue;
                    Core.Parsing.Format outputItem;
                    if (!TryEvaluateCondition(parameters[paramIndex], currentNumber, out conditionWasTrue, out outputItem))
                    {
                        // This parameter doesn't have a
                        // complex condition (making it a "else" condition)

                        // Only do "complex conditions" if the first item IS a "complex condition".
                        if (paramIndex == 0)
                        {
                            break;
                        }
                        // Otherwise, output the "else" section:
                        conditionWasTrue = true;
                    }

                    // If the conditional statement was true, then we can break.
                    if (conditionWasTrue)
                    {
                        formatDetails.Formatter.Format(output, outputItem, current, formatDetails);
                        handled = true;
                        return;
                    }
                }
                // We don't have any "complex conditions",
                // so let's do the normal conditional formatting:
            }


            var paramCount = parameters.Count;

            // Determine the Current item's Type:
            if (currentIsNumber)
            {
                if (currentNumber < 0)
                {
                    paramIndex = paramCount - 1;
                }
                else
                {
                    paramIndex = Math.Min((int)Math.Floor(currentNumber), paramCount - 1);
                }
            }
            else if (current is bool)
            {
                // Bool: True|False
                bool arg = (bool)current;
                if (arg)
                {
                    paramIndex = 0;
                }
                else
                {
                    paramIndex = 1;
                }
            }
            else if (current is DateTime)
            {
                // Date: Past|Present|Future   or   Past/Present|Future
                System.DateTime arg = (DateTime)current;
                if (paramCount == 3 && arg.Date == DateTime.Today)
                {
                    paramIndex = 1;
                }
                else if (arg <= DateTime.Now)
                {
                    paramIndex = 0;
                }
                else
                {
                    paramIndex = paramCount - 1;
                }
            }
            else if (current is TimeSpan)
            {
                // TimeSpan: Negative|Zero|Positive  or  Negative/Zero|Positive
                TimeSpan arg = (TimeSpan)current;
                if (paramCount == 3 && arg == TimeSpan.Zero)
                {
                    paramIndex = 1;
                }
                else if (arg.CompareTo(TimeSpan.Zero) <= 0)
                {
                    paramIndex = 0;
                }
                else
                {
                    paramIndex = paramCount - 1;
                }
            }
            else if (current is string)
            {
                // String: Value|NullOrEmpty
                var arg = (string)current;
                if (!string.IsNullOrEmpty(arg))
                {
                    paramIndex = 0;
                }
                else
                {
                    paramIndex = 1;
                }
            }
            else
            {
                // Object: Something|Nothing
                object arg = current;
                if (arg != null)
                {
                    paramIndex = 0;
                }
                else
                {
                    paramIndex = 1;
                }
            }

            // Now, output the selected parameter:
            var selectedParameter = parameters[paramIndex];

            // Output the selectedParameter:
            formatDetails.Formatter.Format(output, selectedParameter, current, formatDetails);
            handled = true;
        }