1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.internal.app;
18 
19 import android.annotation.IntRange;
20 import android.compat.annotation.UnsupportedAppUsage;
21 import android.icu.text.CaseMap;
22 import android.icu.text.ListFormatter;
23 import android.icu.util.ULocale;
24 import android.os.LocaleList;
25 import android.text.TextUtils;
26 
27 import java.text.Collator;
28 import java.util.Comparator;
29 import java.util.Locale;
30 
31 /**
32  * This class implements some handy methods to process with locales.
33  */
34 public class LocaleHelper {
35 
36     /**
37      * Sentence-case (first character uppercased).
38      *
39      * @param str the string to sentence-case.
40      * @param locale the locale used for the case conversion.
41      * @return the string converted to sentence-case.
42      */
toSentenceCase(String str, Locale locale)43     public static String toSentenceCase(String str, Locale locale) {
44         // Titlecases only the character at index 0, don't touch anything else
45         return CaseMap.toTitle().wholeString().noLowercase().apply(locale, null, str);
46     }
47 
48     /**
49      * Normalizes a string for locale name search. Does case conversion for now,
50      * but might do more in the future.
51      *
52      * <p>Warning: it is only intended to be used in searches by the locale picker.
53      * Don't use it for other things, it is very limited.</p>
54      *
55      * @param str the string to normalize
56      * @param locale the locale that might be used for certain operations (i.e. case conversion)
57      * @return the string normalized for search
58      */
59     @UnsupportedAppUsage
normalizeForSearch(String str, Locale locale)60     public static String normalizeForSearch(String str, Locale locale) {
61         // TODO: tbd if it needs to be smarter (real normalization, remove accents, etc.)
62         // If needed we might use case folding and ICU/CLDR's collation-based loose searching.
63         // TODO: decide what should the locale be, the default locale, or the locale of the string.
64         // Uppercase is better than lowercase because of things like sharp S, Greek sigma, ...
65         return str.toUpperCase();
66     }
67 
68     // For some locales we want to use a "dialect" form, for instance
69     // "Dari" instead of "Persian (Afghanistan)", or "Moldavian" instead of "Romanian (Moldova)"
shouldUseDialectName(Locale locale)70     private static boolean shouldUseDialectName(Locale locale) {
71         final String lang = locale.getLanguage();
72         return "fa".equals(lang) // Persian
73                 || "ro".equals(lang) // Romanian
74                 || "zh".equals(lang); // Chinese
75     }
76 
77     /**
78      * Returns the locale localized for display in the provided locale.
79      *
80      * @param locale the locale whose name is to be displayed.
81      * @param displayLocale the locale in which to display the name.
82      * @param sentenceCase true if the result should be sentence-cased
83      * @return the localized name of the locale.
84      */
85     @UnsupportedAppUsage
getDisplayName(Locale locale, Locale displayLocale, boolean sentenceCase)86     public static String getDisplayName(Locale locale, Locale displayLocale, boolean sentenceCase) {
87         final ULocale displayULocale = ULocale.forLocale(displayLocale);
88         String result = shouldUseDialectName(locale)
89                 ? ULocale.getDisplayNameWithDialect(locale.toLanguageTag(), displayULocale)
90                 : ULocale.getDisplayName(locale.toLanguageTag(), displayULocale);
91         return sentenceCase ? toSentenceCase(result, displayLocale) : result;
92     }
93 
94     /**
95      * Returns the locale localized for display in the default locale.
96      *
97      * @param locale the locale whose name is to be displayed.
98      * @param sentenceCase true if the result should be sentence-cased
99      * @return the localized name of the locale.
100      */
getDisplayName(Locale locale, boolean sentenceCase)101     public static String getDisplayName(Locale locale, boolean sentenceCase) {
102         return getDisplayName(locale, Locale.getDefault(), sentenceCase);
103     }
104 
105     /**
106      * Returns a locale's country localized for display in the provided locale.
107      *
108      * @param locale the locale whose country will be displayed.
109      * @param displayLocale the locale in which to display the name.
110      * @return the localized country name.
111      */
112     @UnsupportedAppUsage
getDisplayCountry(Locale locale, Locale displayLocale)113     public static String getDisplayCountry(Locale locale, Locale displayLocale) {
114         final String languageTag = locale.toLanguageTag();
115         final ULocale uDisplayLocale = ULocale.forLocale(displayLocale);
116         final String country = ULocale.getDisplayCountry(languageTag, uDisplayLocale);
117         final String numberingSystem = locale.getUnicodeLocaleType("nu");
118         if (numberingSystem != null) {
119             return String.format("%s (%s)", country,
120                     ULocale.getDisplayKeywordValue(languageTag, "numbers", uDisplayLocale));
121         } else {
122             return country;
123         }
124     }
125 
126     /**
127      * Returns a locale's country localized for display in the default locale.
128      *
129      * @param locale the locale whose country will be displayed.
130      * @return the localized country name.
131      */
getDisplayCountry(Locale locale)132     public static String getDisplayCountry(Locale locale) {
133         return ULocale.getDisplayCountry(locale.toLanguageTag(), ULocale.getDefault());
134     }
135 
136     /**
137      * Returns the locale list localized for display in the provided locale.
138      *
139      * @param locales the list of locales whose names is to be displayed.
140      * @param displayLocale the locale in which to display the names.
141      *                      If this is null, it will use the default locale.
142      * @param maxLocales maximum number of locales to display. Generates ellipsis after that.
143      * @return the locale aware list of locale names
144      */
getDisplayLocaleList( LocaleList locales, Locale displayLocale, @IntRange(from=1) int maxLocales)145     public static String getDisplayLocaleList(
146             LocaleList locales, Locale displayLocale, @IntRange(from=1) int maxLocales) {
147 
148         final Locale dispLocale = displayLocale == null ? Locale.getDefault() : displayLocale;
149 
150         final boolean ellipsisNeeded = locales.size() > maxLocales;
151         final int localeCount, listCount;
152         if (ellipsisNeeded) {
153             localeCount = maxLocales;
154             listCount = maxLocales + 1;  // One extra slot for the ellipsis
155         } else {
156             listCount = localeCount = locales.size();
157         }
158         final String[] localeNames = new String[listCount];
159         for (int i = 0; i < localeCount; i++) {
160             localeNames[i] = LocaleHelper.getDisplayName(locales.get(i), dispLocale, false);
161         }
162         if (ellipsisNeeded) {
163             // Theoretically, we want to extract this from ICU's Resource Bundle for
164             // "Ellipsis/final", which seems to have different strings than the normal ellipsis for
165             // Hong Kong Traditional Chinese (zh_Hant_HK) and Dzongkha (dz). But that has two
166             // problems: it's expensive to extract it, and in case the output string becomes
167             // automatically ellipsized, it can result in weird output.
168             localeNames[maxLocales] = TextUtils.getEllipsisString(TextUtils.TruncateAt.END);
169         }
170 
171         ListFormatter lfn = ListFormatter.getInstance(dispLocale);
172         return lfn.format((Object[]) localeNames);
173     }
174 
175     /**
176      * Adds the likely subtags for a provided locale ID.
177      *
178      * @param locale the locale to maximize.
179      * @return the maximized Locale instance.
180      */
addLikelySubtags(Locale locale)181     public static Locale addLikelySubtags(Locale locale) {
182         return ULocale.addLikelySubtags(ULocale.forLocale(locale)).toLocale();
183     }
184 
185     /**
186      * Locale-sensitive comparison for LocaleInfo.
187      *
188      * <p>It uses the label, leaving the decision on what to put there to the LocaleInfo.
189      * For instance fr-CA can be shown as "français" as a generic label in the language selection,
190      * or "français (Canada)" if it is a suggestion, or "Canada" in the country selection.</p>
191      *
192      * <p>Gives priority to suggested locales (to sort them at the top).</p>
193      */
194     public static final class LocaleInfoComparator implements Comparator<LocaleStore.LocaleInfo> {
195         private final Collator mCollator;
196         private final boolean mCountryMode;
197         private static final String PREFIX_ARABIC = "\u0627\u0644"; // ALEF-LAM, ال
198 
199         /**
200          * Constructor.
201          *
202          * @param sortLocale the locale to be used for sorting.
203          */
204         @UnsupportedAppUsage
LocaleInfoComparator(Locale sortLocale, boolean countryMode)205         public LocaleInfoComparator(Locale sortLocale, boolean countryMode) {
206             mCollator = Collator.getInstance(sortLocale);
207             mCountryMode = countryMode;
208         }
209 
210         /*
211          * The Arabic collation should ignore Alef-Lam at the beginning (b/26277596)
212          *
213          * We look at the label's locale, not the current system locale.
214          * This is because the name of the Arabic language itself is in Arabic,
215          * and starts with Alef-Lam, no matter what the system locale is.
216          */
removePrefixForCompare(Locale locale, String str)217         private String removePrefixForCompare(Locale locale, String str) {
218             if ("ar".equals(locale.getLanguage()) && str.startsWith(PREFIX_ARABIC)) {
219                 return str.substring(PREFIX_ARABIC.length());
220             }
221             return str;
222         }
223 
224         /**
225          * Compares its two arguments for order.
226          *
227          * @param lhs   the first object to be compared
228          * @param rhs   the second object to be compared
229          * @return  a negative integer, zero, or a positive integer as the first
230          *          argument is less than, equal to, or greater than the second.
231          */
232         @UnsupportedAppUsage
233         @Override
compare(LocaleStore.LocaleInfo lhs, LocaleStore.LocaleInfo rhs)234         public int compare(LocaleStore.LocaleInfo lhs, LocaleStore.LocaleInfo rhs) {
235             // We don't care about the various suggestion types, just "suggested" (!= 0)
236             // and "all others" (== 0)
237             if (lhs.isSuggested() == rhs.isSuggested()) {
238                 // They are in the same "bucket" (suggested / others), so we compare the text
239                 return mCollator.compare(
240                         removePrefixForCompare(lhs.getLocale(), lhs.getLabel(mCountryMode)),
241                         removePrefixForCompare(rhs.getLocale(), rhs.getLabel(mCountryMode)));
242             } else {
243                 // One locale is suggested and one is not, so we put them in different "buckets"
244                 return lhs.isSuggested() ? -1 : 1;
245             }
246         }
247     }
248 }
249