public CultureDisplayNames GetCultureDisplayNames(UCultureInfo uCulture, DisplayContextOptions options) { return(cache.GetOrCreate(new Tuple <UCultureInfo, DisplayContextOptions>(uCulture, options), (key) => { return new DataTableCultureDisplayNames(key.Item1, key.Item2); })); }
/// <summary> /// Constructor, normally only called internally. /// </summary> /// <param name="minimized">Locale for an input locale.</param> /// <param name="modified">Modified for an input locale.</param> /// <param name="nameInDisplayLocale">Name of the modified locale in the display locale.</param> /// <param name="nameInSelf">Name of the modified locale in itself.</param> /// <stable>ICU 55</stable> public UiListItem(UCultureInfo minimized, UCultureInfo modified, string nameInDisplayLocale, string nameInSelf) { this.Minimized = minimized; this.Modified = modified; this.NameInDisplayLocale = nameInDisplayLocale; this.NameInSelf = nameInSelf; }
internal LastResortCultureDisplayNames(UCultureInfo culture, DisplayContextOptions options) #pragma warning disable 612, 618 : base() #pragma warning restore 612, 618 { this.culture = culture; this.options = options; }
public IDataTable GetDataTable(UCultureInfo culture, bool nullIfNotFound) { if (HasData) { return(defaultDataTableProvider.GetDataTable(culture, nullIfNotFound)); } return(new DataTable(nullIfNotFound)); }
public static CultureInfo ToCultureInfo(UCultureInfo uloc) { var baseName = uloc.Name; if (baseName.Equals("root", StringComparison.OrdinalIgnoreCase) || baseName.Equals("any", StringComparison.OrdinalIgnoreCase)) { return(CultureInfo.InvariantCulture); } bool isCollationValue = false; uloc.Keywords.TryGetValue("collation", out string collationValue); foreach (var collation in CollationMapData) { if (baseName.Equals(collation[1], StringComparison.Ordinal) || baseName.Equals(collation[4], StringComparison.Ordinal)) { if (collation[2] == null || collationValue != null && collationValue.Equals(collation[3])) { baseName = collation[0]; isCollationValue = true; break; } } } try { // ICU4N TODO: Apply calendars, numbers, etc before returning if (isCollationValue) { return(new CultureInfo(baseName)); } else { return(new CultureInfo(ICUBaseNameToCultureInfoName(baseName))); } } catch (CultureNotFoundException) { // Fallback to original base name(collation not supported) //baseName = uloc.Name; } try { // ICU4N TODO: Apply calendars, numbers, etc before returning return(new CultureInfo(ICUBaseNameToCultureInfoName(uloc.Name))); } catch (CultureNotFoundException) { // Fallback return(ToCultureInfo(uloc.GetParent() ?? UCultureInfo.InvariantCulture)); } }
/** * Resets the <code>Builder</code> to match the provided * <code>locale</code>. Existing state is discarded. * * <para/>All fields of the locale must be well-formed, see {@link Locale}. * * <para/>Locales with any ill-formed fields cause * <code>IllformedLocaleException</code> to be thrown. * * @param locale the locale * @return This builder. * @throws IllformedLocaleException if <code>locale</code> has * any ill-formed fields. * @throws NullPointerException if <code>locale</code> is null. * * @stable ICU 4.2 */ public UCultureInfoBuilder SetCulture(UCultureInfo locale) { try { _locbld.SetLocale(locale.Base, locale.LocaleExtensions); } catch (FormatException e) { throw new IllformedLocaleException(e.ToString(), e); } return(this); }
internal static IDictionary <string, string> LoadNonGregorianDefaultCalendars() { var result = new Dictionary <string, string>(StringComparer.Ordinal); var supportedCultures = UCultureInfo.GetCultures(UCultureTypes.AllCultures); foreach (var culture in supportedCultures) { var defaultCalendar = GetDefaultCalendarFromBundle(culture.Name); if (!defaultCalendar.Equals("gregorian", StringComparison.Ordinal)) { result[culture.Name] = defaultCalendar; } } return(result); }
private UiListItem NewRow(UCultureInfo modified, Capitalization capitalization) { #pragma warning disable 612, 618 UCultureInfo minimized = UCultureInfo.MinimizeSubtags(modified, UCultureInfo.Minimize.FavorScript); #pragma warning restore 612, 618 string tempName = modified.GetDisplayName(locale); bool titlecase = capitalization == Capitalization.UIListOrMenu; string nameInDisplayLocale = titlecase ? ToTitleWholeStringNoLowercase(locale, tempName) : tempName; tempName = modified.GetDisplayName(modified); string nameInSelf = capitalization == Capitalization.UIListOrMenu ? ToTitleWholeStringNoLowercase(modified, tempName) : tempName; return(new UiListItem(minimized, modified, nameInDisplayLocale, nameInSelf)); }
/// <summary> /// Returns an instance of <see cref="CultureDisplayNames"/> that /// returns names formatted for the provided <paramref name="locale"/>, /// using the provided <see cref="DisplayContextOptions"/> settings. /// </summary> /// <param name="locale">The display locale.</param> /// <param name="options">One or more context settings (e.g. for dialect handling, capitalization, etc.)</param> /// <returns>A <see cref="CultureDisplayNames"/> instance.</returns> /// <draft>ICU 60</draft> public static CultureDisplayNames GetInstance(UCultureInfo locale, DisplayContextOptions options) { CultureDisplayNames result = null; var culture = locale; //.ToUCultureInfo(); options = options.Freeze(); if (cultureDisplayNamesFactory != null) { result = cultureDisplayNamesFactory.GetCultureDisplayNames(culture, options); } if (result == null) { result = new LastResortCultureDisplayNames(culture, options); } return(result); }
/// <summary> /// Creates a <see cref="UCultureInfo"/> that represents the specific culture /// that is associated with the specified name. /// </summary> /// <param name="name">A predefined locale ID or the name of an existing <see cref="ToCultureInfo"/> object. /// <paramref name="name"/> is not case-sensitive.</param> /// <returns>A <see cref="UCultureInfo"/> objec that represents: /// <para/> /// The invariant culture, if <paramref name="name"/> is an empty string. /// <para/> /// -or- /// <para/> /// The specific culture associated with <paramref name="name"/>, if <paramref name="name"/> is a neutral culture. /// <para/> /// -or- /// <para/> /// The culture specified by <paramref name="name"/>, if <paramref name="name"/> is already a specific culture. /// </returns> // Return a specific culture. A tad irrelevent now since we always // return valid data for neutral locales. // // Note that there's interesting behavior that tries to find a // smaller name, ala RFC4647, if we can't find a bigger name. // That doesn't help with things like "zh" though, so the approach // is of questionable value public /*new*/ static UCultureInfo CreateSpecificCulture(string name) { UCultureInfo culture; try { culture = new UCultureInfo(name); } catch (ArgumentException) { // When CultureInfo throws this exception, it may be because someone passed the form // like "az-az" because it came out of an http accept lang. We should try a little // parsing to perhaps fall back to "az" here and use *it* to create the neutral. culture = null; for (int idx = 0; idx < name.Length; idx++) { if ('-' == name[idx] || '_' == name[idx]) { try { culture = new UCultureInfo(name.Substring(0, idx)); break; } catch (ArgumentException) { // throw the original exception so the name in the string will be right throw; } } } if (culture == null) { // nothing to save here; throw the original exception throw; } } // In the most common case, they've given us a specific culture, so we'll just return that. if (!culture.IsNeutralCulture) { return(culture); } return(new UCultureInfo(culture.FullName)); }
/// <summary> /// Initializes a new instance of <see cref="UCultureInfo"/> /// based on the <see cref="UCultureInfo"/> specified by the <paramref name="culture"/> identifier. /// </summary> /// <param name="culture">A <see cref="UCultureInfo"/> object. This value will be applied /// to the <see cref="UCultureInfo.CurrentCulture"/>. /// </param> /// <param name="uiCulture">A <see cref="UCultureInfo"/> object. This value will be applied /// to the <see cref="UCultureInfo.CurrentUICulture"/>.</param> public ThreadCultureChange(UCultureInfo culture, UCultureInfo uiCulture) { if (culture == null) { throw new ArgumentNullException(nameof(culture)); } if (uiCulture == null) { throw new ArgumentNullException(nameof(uiCulture)); } // Record the current culture settings so they can be restored later. this.originalCulture = UCultureInfo.CurrentCulture; this.originalUICulture = UCultureInfo.CurrentUICulture; // Set both the culture and UI culture for this context. UCultureInfo.CurrentCulture = culture; UCultureInfo.CurrentUICulture = uiCulture; }
public void TestCurrentCulturesAsync() { var newCurrentCulture = new UCultureInfo(UCultureInfo.CurrentCulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP"); var newCurrentUICulture = new UCultureInfo(UCultureInfo.CurrentUICulture.Name.Equals("ja-JP", StringComparison.OrdinalIgnoreCase) ? "en-US" : "ja-JP"); using (new ThreadCultureChange(newCurrentCulture, newCurrentUICulture)) { #if FEATURE_TASK_RUN Task t = Task.Run(() => #else Task t = Task.Factory.StartNew(() => #endif { Assert.AreEqual(UCultureInfo.CurrentCulture, newCurrentCulture); Assert.AreEqual(UCultureInfo.CurrentUICulture, newCurrentUICulture); #if FEATURE_TASK_RUN }); #else }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
/// <summary> /// Initializes a new instance of <see cref="UCultureInfo"/> /// based on the <see cref="UCultureInfo"/> specified by the <paramref name="culture"/> identifier. /// </summary> /// <param name="culture">A <see cref="UCultureInfo"/> object. This value will be applied /// to the <see cref="UCultureInfo.CurrentCulture"/>. /// </param> public ThreadCultureChange(UCultureInfo culture) : this(culture, UCultureInfo.CurrentUICulture) { }
/// <summary> /// Gets the table data from the provider. /// </summary> /// <param name="culture">The culture of the table data to retrieve.</param> /// <param name="nullIfNotFound">If <c>true</c>, this method returns <c>null</c> /// when the data is not available in the provider. If <c>false</c>, the code /// that is passed in will be returned.</param> /// <returns>The table data.</returns> /// <draft>ICU 60</draft> public virtual IDataTable GetDataTable(UCultureInfo culture, bool nullIfNotFound) { return(new ICUDataTable(ICUData.IcuRegionBaseName, culture, Assembly, nullIfNotFound)); }
public static CultureInfo Fallback(UCultureInfo locale) { return(Fallback(locale.FullName)); }
// factory methods /// <summary> /// Convenience overload of <see cref="GetInstance(UCultureInfo, DialectHandling)"/> that specifies /// <see cref="DialectHandling.StandardNames"/> dialect handling. /// </summary> /// <param name="locale">The display locale.</param> /// <returns>A <see cref="CultureDisplayNames"/> instance.</returns> /// <draft>ICU 60</draft> public static CultureDisplayNames GetInstance(UCultureInfo locale) { return(GetInstance(locale, DialectHandling.StandardNames)); }
public override string GetLocaleDisplayName(UCultureInfo locale) { return(locale.FullName); }
public override string GetLocaleDisplayName(UCultureInfo locale) { return(GetLocaleDisplayNameInternal(locale)); }
// names for entire locales /// <summary> /// Returns the display name of the provided <paramref name="locale"/>. /// When no display names are available for all or portions /// of the original locale ID, those portions may be /// used directly (possibly in a more canonical form) as /// part of the returned display name. /// </summary> /// <param name="locale">The locale whose display name to return.</param> /// <returns>The display name of the provided <paramref name="locale"/>.</returns> /// <draft>ICU 60</draft> public abstract string GetLocaleDisplayName(UCultureInfo locale);
private static string ToTitleWholeStringNoLowercase(UCultureInfo culture, string s) { return(ToTitleWholeStringNoLower.Apply( culture.ToCultureInfo(), null, s, new StringBuilder(), null).ToString()); }
public override IList <UiListItem> GetUiListCompareWholeItems(ICollection <UCultureInfo> cultures, IComparer <UiListItem> comparer) { Capitalization capContext = displayContextOptions.Capitalization; List <UiListItem> result = new List <UiListItem>(); IDictionary <UCultureInfo, ISet <UCultureInfo> > baseToLocales = new Dictionary <UCultureInfo, ISet <UCultureInfo> >(); UCultureInfoBuilder builder = new UCultureInfoBuilder(); foreach (var locOriginal in cultures) { builder.SetCulture(locOriginal); // verify well-formed. We do this here so that we consistently throw exception UCultureInfo loc = UCultureInfo.AddLikelySubtags(locOriginal); UCultureInfo @base = new UCultureInfo(loc.Language); if (!baseToLocales.TryGetValue(@base, out ISet <UCultureInfo> locales) || locales == null) { baseToLocales[@base] = locales = new JCG.HashSet <UCultureInfo>(1); } locales.Add(loc); } foreach (var entry in baseToLocales) { UCultureInfo @base = entry.Key; ISet <UCultureInfo> values = entry.Value; if (values.Count == 1) { UCultureInfo locale = values.First(); #pragma warning disable 612, 618 result.Add(NewRow(UCultureInfo.MinimizeSubtags(locale, UCultureInfo.Minimize.FavorScript), capContext)); #pragma warning restore 612, 618 } else { ISet <string> scripts = new JCG.HashSet <string>(values.Count + 1); ISet <string> regions = new JCG.HashSet <string>(values.Count + 1); // need the follow two steps to make sure that unusual scripts or regions are displayed UCultureInfo maxBase = UCultureInfo.AddLikelySubtags(@base); scripts.Add(maxBase.Script); regions.Add(maxBase.Country); foreach (UCultureInfo locale in values) { scripts.Add(locale.Script); regions.Add(locale.Country); } bool hasScripts = scripts.Count > 1; bool hasRegions = regions.Count > 1; foreach (UCultureInfo locale in values) { UCultureInfoBuilder modified = builder.SetCulture(locale); if (!hasScripts) { modified.SetScript(""); } if (!hasRegions) { modified.SetRegion(""); } result.Add(NewRow(modified.Build(), capContext)); } } } result.Sort(comparer); return(result); }
// TODO: implement use of capitalization private string GetLocaleDisplayNameInternal(UCultureInfo locale) { // lang // lang (script, country, variant, keyword=value, ...) // script, country, variant, keyword=value, ... string resultName = null; string lang = locale.Language; // 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.Name.Length == 0) { lang = "root"; } string script = locale.Script; string country = locale.Country; string variant = locale.Variant; bool hasScript = script.Length > 0; bool hasCountry = country.Length > 0; bool hasVariant = variant.Length > 0; // always have a value for lang if (displayContextOptions.DialectHandling == DialectHandling.DialectNames) { 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 = GetScriptDisplayNameInContext(script, true); if (result == null) { return(null); } buf.Append(result .Replace(formatOpenParen, formatReplaceOpenParen) .Replace(formatCloseParen, formatReplaceCloseParen)); } if (hasCountry) { string result = GetRegionDisplayName(country, true); if (result == null) { return(null); } AppendWithSep(result .Replace(formatOpenParen, formatReplaceOpenParen) .Replace(formatCloseParen, formatReplaceCloseParen), buf); } if (hasVariant) { string result = GetVariantDisplayName(variant, true); if (result == null) { return(null); } AppendWithSep(result .Replace(formatOpenParen, formatReplaceOpenParen) .Replace(formatCloseParen, formatReplaceCloseParen), buf); } using (var pairs = locale.Keywords.GetEnumerator()) { if (pairs != null) { while (pairs.MoveNext()) { string key = pairs.Current.Key; string value = pairs.Current.Value; // locale.GetKeywordValue(key); string keyDisplayName = GetKeyDisplayName(key, true); if (keyDisplayName == null) { return(null); } keyDisplayName = keyDisplayName .Replace(formatOpenParen, formatReplaceOpenParen) .Replace(formatCloseParen, formatReplaceCloseParen); string valueDisplayName = GetKeyValueDisplayName(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)); }
public ICUDataTable(string path, UCultureInfo culture, Assembly assembly, bool nullIfNotFound) : base(nullIfNotFound) { this.bundle = (ICUResourceBundle)UResourceBundle.GetBundleInstance( path, culture.Name, assembly); }
/** * Returns an instance of <code>UCultureInfo</code> created from the fields set * on this builder. * * @return a new CultureInfo * * @stable ICU 4.4 */ public UCultureInfo Build() { return(UCultureInfo.GetInstance(_locbld.GetBaseLocale(), _locbld.GetLocaleExtensions())); }
public DataTableCultureDisplayNames(UCultureInfo culture, DisplayContextOptions options) #pragma warning disable 612, 618 : base() #pragma warning restore 612, 618 { this.displayContextOptions = options.Freeze(); this.langData = languageDataTableProvider.GetDataTable(culture, options.SubstituteHandling == SubstituteHandling.NoSubstitute); this.regionData = regionDataTableProvider.GetDataTable(culture, options.SubstituteHandling == SubstituteHandling.NoSubstitute); this.locale = langData.CultureInfo != null && langData.CultureInfo.Equals(CultureInfo.InvariantCulture) ? regionData.CultureInfo.ToUCultureInfo() : langData.CultureInfo.ToUCultureInfo(); // Note, by going through DataTable, this uses table lookup rather than straight lookup. // That should get us the same data, I think. This way we don't have to explicitly // load the bundle again. Using direct lookup didn't seem to make an appreciable // difference in performance. string sep = langData.Get("localeDisplayPattern", "separator"); if (sep == null || "separator".Equals(sep)) { sep = "{0}, {1}"; } StringBuilder sb = new StringBuilder(); this.separatorFormat = SimpleFormatterImpl.CompileToStringMinMaxArguments(sep, sb, 2, 2); string pattern = langData.Get("localeDisplayPattern", "pattern"); if (pattern == null || "pattern".Equals(pattern)) { pattern = "{0} ({1})"; } this.format = SimpleFormatterImpl.CompileToStringMinMaxArguments(pattern, sb, 2, 2); if (pattern.Contains("(")) { formatOpenParen = '('; formatCloseParen = ')'; formatReplaceOpenParen = '['; formatReplaceCloseParen = ']'; } else { formatOpenParen = '('; formatCloseParen = ')'; formatReplaceOpenParen = '['; formatReplaceCloseParen = ']'; } string keyTypePattern = langData.Get("localeDisplayPattern", "keyTypePattern"); if (keyTypePattern == null || "keyTypePattern".Equals(keyTypePattern)) { keyTypePattern = "{0}={1}"; } this.keyTypeFormat = SimpleFormatterImpl.CompileToStringMinMaxArguments( keyTypePattern, sb, 2, 2); // Get values from the contextTransforms data if we need them // Also check whether we will need a break iterator (depends on the data) bool needBrkIter = false; if (options.Capitalization == Capitalization.UIListOrMenu || options.Capitalization == Capitalization.Standalone) { capitalizationUsage = new bool[Enum.GetValues(typeof(CapitalizationContextUsage)).Length]; // initialized to all false ICUResourceBundle rb = (ICUResourceBundle)UResourceBundle.GetBundleInstance(ICUData.IcuBaseName, locale); CapitalizationContextSink sink = new CapitalizationContextSink(this); try { rb.GetAllItemsWithFallback("contextTransforms", sink); } catch (MissingManifestResourceException) { // Silently ignore. Not every locale has contextTransforms. } needBrkIter = sink.hasCapitalizationUsage; } // Get a sentence break iterator if we will need it if (needBrkIter || options.Capitalization == Capitalization.BeginningOfSentence) { capitalizationBrkIter = BreakIterator.GetSentenceInstance(locale); } this.currencyDisplayInfo = CurrencyData.Provider.GetInstance(locale, false); }