示例#1
0
        /// <summary>
        /// Returns a currency object for the default currency in the given locale.
        /// </summary>
        ///
        /// @stable ICU 3.2
        public static Currency GetInstance(ULocale locale)
        {
            String currency = locale.GetKeywordValue("currency");

            if (currency != null)
            {
                return(GetInstance(currency));
            }

            if (shim == null)
            {
                return(CreateCurrency(locale));
            }

            return(shim.CreateInstance(locale));
        }
示例#2
0
        /// <summary>
        /// Returns the default numbering system for the specified <see cref="ULocale"/>.
        /// </summary>
        /// <stable>ICU 4.2</stable>
        public static NumberingSystem GetInstance(ULocale locale)
        {
            // Check for @numbers
            bool   nsResolved     = true;
            string numbersKeyword = locale.GetKeywordValue("numbers");

            if (numbersKeyword != null)
            {
                foreach (string keyword in OTHER_NS_KEYWORDS)
                {
                    if (numbersKeyword.Equals(keyword))
                    {
                        nsResolved = false;
                        break;
                    }
                }
            }
            else
            {
                numbersKeyword = "default";
                nsResolved     = false;
            }

            if (nsResolved)
            {
                NumberingSystem ns = GetInstanceByName(numbersKeyword);
                if (ns != null)
                {
                    return(ns);
                }
                // If the @numbers keyword points to a bogus numbering system name,
                // we return the default for the locale.
                numbersKeyword = "default";
            }

            // Attempt to get the numbering system from the cache
            string baseName = locale.GetBaseName();
            // TODO: Caching by locale+numbersKeyword could yield a large cache.
            // Try to load for each locale the mappings from OTHER_NS_KEYWORDS and default
            // to real numbering system names; can we get those from supplemental data?
            // Then look up those mappings for the locale and resolve the keyword.
            string           key = baseName + "@numbers=" + numbersKeyword;
            LocaleLookupData localeLookupData = new LocaleLookupData(locale, numbersKeyword);

            return(cachedLocaleData.GetOrCreate(key, (k) => LookupInstanceByLocale(localeLookupData)));
        }
示例#3
0
        // TODO: implement use of capitalization
        private string LocaleDisplayNameInternal(ULocale locale)
        {
            // lang
            // lang (script, country, variant, keyword=value, ...)
            // script, country, variant, keyword=value, ...

            string resultName = null;

            string lang = locale.GetLanguage();

            // Empty basename indicates root locale (keywords are ignored for this).
            // Our data uses 'root' to access display names for the root locale in the
            // "Languages" table.
            if (locale.GetBaseName().Length == 0)
            {
                lang = "root";
            }
            string script  = locale.GetScript();
            string country = locale.GetCountry();
            string variant = locale.GetVariant();

            bool hasScript  = script.Length > 0;
            bool hasCountry = country.Length > 0;
            bool hasVariant = variant.Length > 0;

            // always have a value for lang
            if (dialectHandling == DialectHandling.DIALECT_NAMES)
            {
                do
                { // loop construct is so we can break early out of search
                    if (hasScript && hasCountry)
                    {
                        string langScriptCountry = lang + '_' + script + '_' + country;
                        string result            = LocaleIdName(langScriptCountry);
                        if (result != null && !result.Equals(langScriptCountry))
                        {
                            resultName = result;
                            hasScript  = false;
                            hasCountry = false;
                            break;
                        }
                    }
                    if (hasScript)
                    {
                        string langScript = lang + '_' + script;
                        string result     = LocaleIdName(langScript);
                        if (result != null && !result.Equals(langScript))
                        {
                            resultName = result;
                            hasScript  = false;
                            break;
                        }
                    }
                    if (hasCountry)
                    {
                        string langCountry = lang + '_' + country;
                        string result      = LocaleIdName(langCountry);
                        if (result != null && !result.Equals(langCountry))
                        {
                            resultName = result;
                            hasCountry = false;
                            break;
                        }
                    }
                } while (false);
            }

            if (resultName == null)
            {
                string result = LocaleIdName(lang);
                if (result == null)
                {
                    return(null);
                }
                resultName = result
                             .Replace(formatOpenParen, formatReplaceOpenParen)
                             .Replace(formatCloseParen, formatReplaceCloseParen);
            }

            StringBuilder buf = new StringBuilder();

            if (hasScript)
            {
                // first element, don't need appendWithSep
                string result = ScriptDisplayNameInContext(script, true);
                if (result == null)
                {
                    return(null);
                }
                buf.Append(result
                           .Replace(formatOpenParen, formatReplaceOpenParen)
                           .Replace(formatCloseParen, formatReplaceCloseParen));
            }
            if (hasCountry)
            {
                string result = RegionDisplayName(country, true);
                if (result == null)
                {
                    return(null);
                }
                AppendWithSep(result
                              .Replace(formatOpenParen, formatReplaceOpenParen)
                              .Replace(formatCloseParen, formatReplaceCloseParen), buf);
            }
            if (hasVariant)
            {
                string result = VariantDisplayName(variant, true);
                if (result == null)
                {
                    return(null);
                }
                AppendWithSep(result
                              .Replace(formatOpenParen, formatReplaceOpenParen)
                              .Replace(formatCloseParen, formatReplaceCloseParen), buf);
            }

            using (IEnumerator <string> keys = locale.GetKeywords())
            {
                if (keys != null)
                {
                    while (keys.MoveNext())
                    {
                        string key            = keys.Current;
                        string value          = locale.GetKeywordValue(key);
                        string keyDisplayName = KeyDisplayName(key, true);
                        if (keyDisplayName == null)
                        {
                            return(null);
                        }
                        keyDisplayName = keyDisplayName
                                         .Replace(formatOpenParen, formatReplaceOpenParen)
                                         .Replace(formatCloseParen, formatReplaceCloseParen);
                        string valueDisplayName = KeyValueDisplayName(key, value, true);
                        if (valueDisplayName == null)
                        {
                            return(null);
                        }
                        valueDisplayName = valueDisplayName
                                           .Replace(formatOpenParen, formatReplaceOpenParen)
                                           .Replace(formatCloseParen, formatReplaceCloseParen);
                        if (!valueDisplayName.Equals(value))
                        {
                            AppendWithSep(valueDisplayName, buf);
                        }
                        else if (!key.Equals(keyDisplayName))
                        {
                            string keyValue = SimpleFormatterImpl.FormatCompiledPattern(
                                keyTypeFormat, keyDisplayName, valueDisplayName);
                            AppendWithSep(keyValue, buf);
                        }
                        else
                        {
                            AppendWithSep(keyDisplayName, buf)
                            .Append("=")
                            .Append(valueDisplayName);
                        }
                    }
                }
            }
            string resultRemainder = null;

            if (buf.Length > 0)
            {
                resultRemainder = buf.ToString();
            }

            if (resultRemainder != null)
            {
                resultName = SimpleFormatterImpl.FormatCompiledPattern(
                    format, resultName, resultRemainder);
            }

            return(AdjustForUsageAndContext(CapitalizationContextUsage.LANGUAGE, resultName));
        }
示例#4
0
        public static CollationTailoring LoadTailoring(ULocale locale, out ULocale outValidLocale)
        {
            // Java porting note: ICU4J getWithFallback/getStringWithFallback currently does not
            // work well when alias table is involved in a resource path, unless full path is specified.
            // For now, collation resources does not contain such data, so the code below should work fine.

            CollationTailoring root       = CollationRoot.Root;
            string             localeName = locale.GetName();

            if (localeName.Length == 0 || localeName.Equals("root"))
            {
                outValidLocale = ULocale.ROOT;
                return(root);
            }

            UResourceBundle bundle = null;

            try
            {
                bundle = ICUResourceBundle.GetBundleInstance(
                    ICUData.ICU_COLLATION_BASE_NAME, locale,
                    // ICU4N specific - need to pass in this assembly
                    // name for the resources to be resolved here.
                    CollationData.ICU_DATA_CLASS_LOADER,
                    ICUResourceBundle.OpenType.LOCALE_ROOT);
            }
            catch (MissingManifestResourceException e)
            {
                outValidLocale = ULocale.ROOT;
                return(root);
            }

            ULocale validLocale = bundle.GetULocale();
            // Normalize the root locale. See
            // http://bugs.icu-project.org/trac/ticket/10715
            string validLocaleName = validLocale.GetName();

            if (validLocaleName.Length == 0 || validLocaleName.Equals("root"))
            {
                validLocale = ULocale.ROOT;
            }
            outValidLocale = validLocale;

            // There are zero or more tailorings in the collations table.
            UResourceBundle collations;

            try
            {
                collations = bundle.Get("collations");
                if (collations == null)
                {
                    return(root);
                }
            }
            catch (MissingManifestResourceException ignored)
            {
                return(root);
            }

            // Fetch the collation type from the locale ID and the default type from the data.
            string type        = locale.GetKeywordValue("collation");
            string defaultType = "standard";

            string defT = ((ICUResourceBundle)collations).FindStringWithFallback("default");

            if (defT != null)
            {
                defaultType = defT;
            }

            if (type == null || type.Equals("default"))
            {
                type = defaultType;
            }
            else
            {
                type = ASCII.ToLower(type);
            }

            // Load the collations/type tailoring, with type fallback.

            // Java porting note: typeFallback is used for setting U_USING_DEFAULT_WARNING in
            // ICU4C, but not used by ICU4J

            // boolean typeFallback = false;
            UResourceBundle data = FindWithFallback(collations, type);

            if (data == null &&
                type.Length > 6 && type.StartsWith("search", StringComparison.Ordinal))
            {
                // fall back from something like "searchjl" to "search"
                // typeFallback = true;
                type = "search";
                data = FindWithFallback(collations, type);
            }

            if (data == null && !type.Equals(defaultType))
            {
                // fall back to the default type
                // typeFallback = true;
                type = defaultType;
                data = FindWithFallback(collations, type);
            }

            if (data == null && !type.Equals("standard"))
            {
                // fall back to the "standard" type
                // typeFallback = true;
                type = "standard";
                data = FindWithFallback(collations, type);
            }

            if (data == null)
            {
                return(root);
            }

            // Is this the same as the root collator? If so, then use that instead.
            ULocale actualLocale = data.GetULocale();
            // http://bugs.icu-project.org/trac/ticket/10715 ICUResourceBundle(root).getULocale() != ULocale.ROOT
            // Therefore not just if (actualLocale.equals(ULocale.ROOT) && type.equals("standard")) {
            string actualLocaleName = actualLocale.GetName();

            if (actualLocaleName.Length == 0 || actualLocaleName.Equals("root"))
            {
                actualLocale = ULocale.ROOT;
                if (type.Equals("standard"))
                {
                    return(root);
                }
            }

            CollationTailoring t = new CollationTailoring(root.Settings);

            t.ActualLocale = actualLocale;

            // deserialize
            UResourceBundle binary  = data.Get("%%CollationBin");
            ByteBuffer      inBytes = binary.GetBinary();

            try
            {
                CollationDataReader.Read(root, inBytes, t);
            }
            catch (IOException e)
            {
                throw new ICUUncheckedIOException("Failed to load collation tailoring data for locale:"
                                                  + actualLocale + " type:" + type, e);
            }

            // Try to fetch the optional rules string.
            try
            {
                t.SetRulesResource(data.Get("Sequence"));
            }
            catch (MissingManifestResourceException ignored)
            {
            }

            // Set the collation types on the informational locales,
            // except when they match the default types (for brevity and backwards compatibility).
            // For the valid locale, suppress the default type.
            if (!type.Equals(defaultType))
            {
                outValidLocale = validLocale.SetKeywordValue("collation", type);
            }

            // For the actual locale, suppress the default type *according to the actual locale*.
            // For example, zh has default=pinyin and contains all of the Chinese tailorings.
            // zh_Hant has default=stroke but has no other data.
            // For the valid locale "zh_Hant" we need to suppress stroke.
            // For the actual locale "zh" we need to suppress pinyin instead.
            if (!actualLocale.Equals(validLocale))
            {
                // Opening a bundle for the actual locale should always succeed.
                UResourceBundle actualBundle = UResourceBundle.GetBundleInstance(
                    ICUData.ICU_COLLATION_BASE_NAME, actualLocale);
                defT = ((ICUResourceBundle)actualBundle).FindStringWithFallback("collations/default");
                if (defT != null)
                {
                    defaultType = defT;
                }
            }

            if (!type.Equals(defaultType))
            {
                t.ActualLocale = t.ActualLocale.SetKeywordValue("collation", type);
            }

            // if (typeFallback) {
            //     ICU4C implementation sets U_USING_DEFAULT_WARNING here
            // }

            return(t);
        }
示例#5
0
        private static BreakIterator CreateBreakInstance(ULocale locale, int kind)
        {
            RuleBasedBreakIterator iter = null;
            ICUResourceBundle      rb   = ICUResourceBundle.
                                          GetBundleInstance(ICUData.ICU_BRKITR_BASE_NAME, locale,
                                                            ICUResourceBundle.OpenType.LOCALE_ROOT);

            //
            //  Get the binary rules.
            //
            ByteBuffer bytes      = null;
            string     typeKeyExt = null;

            if (kind == BreakIterator.KIND_LINE)
            {
                string lbKeyValue = locale.GetKeywordValue("lb");
                if (lbKeyValue != null && (lbKeyValue.Equals("strict") || lbKeyValue.Equals("normal") || lbKeyValue.Equals("loose")))
                {
                    typeKeyExt = "_" + lbKeyValue;
                }
            }

            try
            {
                string typeKey       = (typeKeyExt == null) ? KIND_NAMES[kind] : KIND_NAMES[kind] + typeKeyExt;
                string brkfname      = rb.GetStringWithFallback("boundaries/" + typeKey);
                string rulesFileName = ICUData.ICU_BRKITR_NAME + '/' + brkfname;
                bytes = ICUBinary.GetData(rulesFileName);
            }
            catch (Exception e)
            {
                throw new MissingManifestResourceException(e.ToString(), e /*, "", ""*/);
            }

            //
            // Create a normal RuleBasedBreakIterator.
            //
            try
            {
#pragma warning disable 612, 618
                iter = RuleBasedBreakIterator.GetInstanceFromCompiledRules(bytes);
#pragma warning restore 612, 618
            }
            catch (IOException e)
            {
                // Shouldn't be possible to get here.
                // If it happens, the compiled rules are probably corrupted in some way.
                Assert.Fail(e);
            }
            // TODO: Determine valid and actual locale correctly.
            ULocale uloc = ULocale.ForLocale(rb.GetLocale());
            iter.SetLocale(uloc, uloc);
            iter.BreakType = kind;

            // filtered break
            if (kind == BreakIterator.KIND_SENTENCE)
            {
                string ssKeyword = locale.GetKeywordValue("ss");
                if (ssKeyword != null && ssKeyword.Equals("standard"))
                {
                    ULocale @base = new ULocale(locale.GetBaseName());
                    return(FilteredBreakIteratorBuilder.GetInstance(@base).WrapIteratorWithFilter(iter));
                }
            }

            return(iter);
        }