• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 android.os;
18 
19 import android.annotation.IntRange;
20 import android.annotation.NonNull;
21 import android.annotation.Nullable;
22 import android.annotation.Size;
23 import android.annotation.UnsupportedAppUsage;
24 import android.content.LocaleProto;
25 import android.icu.util.ULocale;
26 import android.util.proto.ProtoOutputStream;
27 
28 import com.android.internal.annotations.GuardedBy;
29 
30 import java.util.Arrays;
31 import java.util.Collection;
32 import java.util.HashSet;
33 import java.util.Locale;
34 
35 /**
36  * LocaleList is an immutable list of Locales, typically used to keep an ordered list of user
37  * preferences for locales.
38  */
39 public final class LocaleList implements Parcelable {
40     private final Locale[] mList;
41     // This is a comma-separated list of the locales in the LocaleList created at construction time,
42     // basically the result of running each locale's toLanguageTag() method and concatenating them
43     // with commas in between.
44     @NonNull
45     private final String mStringRepresentation;
46 
47     private static final Locale[] sEmptyList = new Locale[0];
48     private static final LocaleList sEmptyLocaleList = new LocaleList();
49 
50     /**
51      * Retrieves the {@link Locale} at the specified index.
52      *
53      * @param index The position to retrieve.
54      * @return The {@link Locale} in the given index.
55      */
get(int index)56     public Locale get(int index) {
57         return (0 <= index && index < mList.length) ? mList[index] : null;
58     }
59 
60     /**
61      * Returns whether the {@link LocaleList} contains no {@link Locale} items.
62      *
63      * @return {@code true} if this {@link LocaleList} has no {@link Locale} items, {@code false}
64      *     otherwise.
65      */
isEmpty()66     public boolean isEmpty() {
67         return mList.length == 0;
68     }
69 
70     /**
71      * Returns the number of {@link Locale} items in this {@link LocaleList}.
72      */
73     @IntRange(from=0)
size()74     public int size() {
75         return mList.length;
76     }
77 
78     /**
79      * Searches this {@link LocaleList} for the specified {@link Locale} and returns the index of
80      * the first occurrence.
81      *
82      * @param locale The {@link Locale} to search for.
83      * @return The index of the first occurrence of the {@link Locale} or {@code -1} if the item
84      *     wasn't found.
85      */
86     @IntRange(from=-1)
indexOf(Locale locale)87     public int indexOf(Locale locale) {
88         for (int i = 0; i < mList.length; i++) {
89             if (mList[i].equals(locale)) {
90                 return i;
91             }
92         }
93         return -1;
94     }
95 
96     @Override
equals(Object other)97     public boolean equals(Object other) {
98         if (other == this)
99             return true;
100         if (!(other instanceof LocaleList))
101             return false;
102         final Locale[] otherList = ((LocaleList) other).mList;
103         if (mList.length != otherList.length)
104             return false;
105         for (int i = 0; i < mList.length; i++) {
106             if (!mList[i].equals(otherList[i]))
107                 return false;
108         }
109         return true;
110     }
111 
112     @Override
hashCode()113     public int hashCode() {
114         int result = 1;
115         for (int i = 0; i < mList.length; i++) {
116             result = 31 * result + mList[i].hashCode();
117         }
118         return result;
119     }
120 
121     @Override
toString()122     public String toString() {
123         StringBuilder sb = new StringBuilder();
124         sb.append("[");
125         for (int i = 0; i < mList.length; i++) {
126             sb.append(mList[i]);
127             if (i < mList.length - 1) {
128                 sb.append(',');
129             }
130         }
131         sb.append("]");
132         return sb.toString();
133     }
134 
135     @Override
describeContents()136     public int describeContents() {
137         return 0;
138     }
139 
140     @Override
writeToParcel(Parcel dest, int parcelableFlags)141     public void writeToParcel(Parcel dest, int parcelableFlags) {
142         dest.writeString(mStringRepresentation);
143     }
144 
145     /**
146      * Helper to write LocaleList to a protocol buffer output stream.  Assumes the parent
147      * protobuf has declared the locale as repeated.
148      *
149      * @param protoOutputStream Stream to write the locale to.
150      * @param fieldId Field Id of the Locale as defined in the parent message.
151      * @hide
152      */
writeToProto(ProtoOutputStream protoOutputStream, long fieldId)153     public void writeToProto(ProtoOutputStream protoOutputStream, long fieldId) {
154         for (int i = 0; i < mList.length; i++) {
155             final Locale locale = mList[i];
156             final long token = protoOutputStream.start(fieldId);
157             protoOutputStream.write(LocaleProto.LANGUAGE, locale.getLanguage());
158             protoOutputStream.write(LocaleProto.COUNTRY, locale.getCountry());
159             protoOutputStream.write(LocaleProto.VARIANT, locale.getVariant());
160             protoOutputStream.write(LocaleProto.SCRIPT, locale.getScript());
161             protoOutputStream.end(token);
162         }
163     }
164 
165     /**
166      * Retrieves a String representation of the language tags in this list.
167      */
168     @NonNull
toLanguageTags()169     public String toLanguageTags() {
170         return mStringRepresentation;
171     }
172 
173     /**
174      * Creates a new {@link LocaleList}.
175      *
176      * <p>For empty lists of {@link Locale} items it is better to use {@link #getEmptyLocaleList()},
177      * which returns a pre-constructed empty list.</p>
178      *
179      * @throws NullPointerException if any of the input locales is <code>null</code>.
180      * @throws IllegalArgumentException if any of the input locales repeat.
181      */
LocaleList(@onNull Locale... list)182     public LocaleList(@NonNull Locale... list) {
183         if (list.length == 0) {
184             mList = sEmptyList;
185             mStringRepresentation = "";
186         } else {
187             final Locale[] localeList = new Locale[list.length];
188             final HashSet<Locale> seenLocales = new HashSet<Locale>();
189             final StringBuilder sb = new StringBuilder();
190             for (int i = 0; i < list.length; i++) {
191                 final Locale l = list[i];
192                 if (l == null) {
193                     throw new NullPointerException("list[" + i + "] is null");
194                 } else if (seenLocales.contains(l)) {
195                     throw new IllegalArgumentException("list[" + i + "] is a repetition");
196                 } else {
197                     final Locale localeClone = (Locale) l.clone();
198                     localeList[i] = localeClone;
199                     sb.append(localeClone.toLanguageTag());
200                     if (i < list.length - 1) {
201                         sb.append(',');
202                     }
203                     seenLocales.add(localeClone);
204                 }
205             }
206             mList = localeList;
207             mStringRepresentation = sb.toString();
208         }
209     }
210 
211     /**
212      * Constructs a locale list, with the topLocale moved to the front if it already is
213      * in otherLocales, or added to the front if it isn't.
214      *
215      * {@hide}
216      */
LocaleList(@onNull Locale topLocale, LocaleList otherLocales)217     public LocaleList(@NonNull Locale topLocale, LocaleList otherLocales) {
218         if (topLocale == null) {
219             throw new NullPointerException("topLocale is null");
220         }
221 
222         final int inputLength = (otherLocales == null) ? 0 : otherLocales.mList.length;
223         int topLocaleIndex = -1;
224         for (int i = 0; i < inputLength; i++) {
225             if (topLocale.equals(otherLocales.mList[i])) {
226                 topLocaleIndex = i;
227                 break;
228             }
229         }
230 
231         final int outputLength = inputLength + (topLocaleIndex == -1 ? 1 : 0);
232         final Locale[] localeList = new Locale[outputLength];
233         localeList[0] = (Locale) topLocale.clone();
234         if (topLocaleIndex == -1) {
235             // topLocale was not in otherLocales
236             for (int i = 0; i < inputLength; i++) {
237                 localeList[i + 1] = (Locale) otherLocales.mList[i].clone();
238             }
239         } else {
240             for (int i = 0; i < topLocaleIndex; i++) {
241                 localeList[i + 1] = (Locale) otherLocales.mList[i].clone();
242             }
243             for (int i = topLocaleIndex + 1; i < inputLength; i++) {
244                 localeList[i] = (Locale) otherLocales.mList[i].clone();
245             }
246         }
247 
248         final StringBuilder sb = new StringBuilder();
249         for (int i = 0; i < outputLength; i++) {
250             sb.append(localeList[i].toLanguageTag());
251             if (i < outputLength - 1) {
252                 sb.append(',');
253             }
254         }
255 
256         mList = localeList;
257         mStringRepresentation = sb.toString();
258     }
259 
260     public static final @android.annotation.NonNull Parcelable.Creator<LocaleList> CREATOR
261             = new Parcelable.Creator<LocaleList>() {
262         @Override
263         public LocaleList createFromParcel(Parcel source) {
264             return LocaleList.forLanguageTags(source.readString());
265         }
266 
267         @Override
268         public LocaleList[] newArray(int size) {
269             return new LocaleList[size];
270         }
271     };
272 
273     /**
274      * Retrieve an empty instance of {@link LocaleList}.
275      */
276     @NonNull
getEmptyLocaleList()277     public static LocaleList getEmptyLocaleList() {
278         return sEmptyLocaleList;
279     }
280 
281     /**
282      * Generates a new LocaleList with the given language tags.
283      *
284      * @param list The language tags to be included as a single {@link String} separated by commas.
285      * @return A new instance with the {@link Locale} items identified by the given tags.
286      */
287     @NonNull
forLanguageTags(@ullable String list)288     public static LocaleList forLanguageTags(@Nullable String list) {
289         if (list == null || list.equals("")) {
290             return getEmptyLocaleList();
291         } else {
292             final String[] tags = list.split(",");
293             final Locale[] localeArray = new Locale[tags.length];
294             for (int i = 0; i < localeArray.length; i++) {
295                 localeArray[i] = Locale.forLanguageTag(tags[i]);
296             }
297             return new LocaleList(localeArray);
298         }
299     }
300 
getLikelyScript(Locale locale)301     private static String getLikelyScript(Locale locale) {
302         final String script = locale.getScript();
303         if (!script.isEmpty()) {
304             return script;
305         } else {
306             // TODO: Cache the results if this proves to be too slow
307             return ULocale.addLikelySubtags(ULocale.forLocale(locale)).getScript();
308         }
309     }
310 
311     private static final String STRING_EN_XA = "en-XA";
312     private static final String STRING_AR_XB = "ar-XB";
313     private static final Locale LOCALE_EN_XA = new Locale("en", "XA");
314     private static final Locale LOCALE_AR_XB = new Locale("ar", "XB");
315     private static final int NUM_PSEUDO_LOCALES = 2;
316 
isPseudoLocale(String locale)317     private static boolean isPseudoLocale(String locale) {
318         return STRING_EN_XA.equals(locale) || STRING_AR_XB.equals(locale);
319     }
320 
321     /**
322      * Returns true if locale is a pseudo-locale, false otherwise.
323      * {@hide}
324      */
isPseudoLocale(Locale locale)325     public static boolean isPseudoLocale(Locale locale) {
326         return LOCALE_EN_XA.equals(locale) || LOCALE_AR_XB.equals(locale);
327     }
328 
329     /**
330      * Returns true if locale is a pseudo-locale, false otherwise.
331      */
isPseudoLocale(@ullable ULocale locale)332     public static boolean isPseudoLocale(@Nullable ULocale locale) {
333         return isPseudoLocale(locale != null ? locale.toLocale() : null);
334     }
335 
336     @IntRange(from=0, to=1)
matchScore(Locale supported, Locale desired)337     private static int matchScore(Locale supported, Locale desired) {
338         if (supported.equals(desired)) {
339             return 1;  // return early so we don't do unnecessary computation
340         }
341         if (!supported.getLanguage().equals(desired.getLanguage())) {
342             return 0;
343         }
344         if (isPseudoLocale(supported) || isPseudoLocale(desired)) {
345             // The locales are not the same, but the languages are the same, and one of the locales
346             // is a pseudo-locale. So this is not a match.
347             return 0;
348         }
349         final String supportedScr = getLikelyScript(supported);
350         if (supportedScr.isEmpty()) {
351             // If we can't guess a script, we don't know enough about the locales' language to find
352             // if the locales match. So we fall back to old behavior of matching, which considered
353             // locales with different regions different.
354             final String supportedRegion = supported.getCountry();
355             return (supportedRegion.isEmpty() ||
356                     supportedRegion.equals(desired.getCountry()))
357                     ? 1 : 0;
358         }
359         final String desiredScr = getLikelyScript(desired);
360         // There is no match if the two locales use different scripts. This will most imporantly
361         // take care of traditional vs simplified Chinese.
362         return supportedScr.equals(desiredScr) ? 1 : 0;
363     }
364 
findFirstMatchIndex(Locale supportedLocale)365     private int findFirstMatchIndex(Locale supportedLocale) {
366         for (int idx = 0; idx < mList.length; idx++) {
367             final int score = matchScore(supportedLocale, mList[idx]);
368             if (score > 0) {
369                 return idx;
370             }
371         }
372         return Integer.MAX_VALUE;
373     }
374 
375     private static final Locale EN_LATN = Locale.forLanguageTag("en-Latn");
376 
computeFirstMatchIndex(Collection<String> supportedLocales, boolean assumeEnglishIsSupported)377     private int computeFirstMatchIndex(Collection<String> supportedLocales,
378             boolean assumeEnglishIsSupported) {
379         if (mList.length == 1) {  // just one locale, perhaps the most common scenario
380             return 0;
381         }
382         if (mList.length == 0) {  // empty locale list
383             return -1;
384         }
385 
386         int bestIndex = Integer.MAX_VALUE;
387         // Try English first, so we can return early if it's in the LocaleList
388         if (assumeEnglishIsSupported) {
389             final int idx = findFirstMatchIndex(EN_LATN);
390             if (idx == 0) { // We have a match on the first locale, which is good enough
391                 return 0;
392             } else if (idx < bestIndex) {
393                 bestIndex = idx;
394             }
395         }
396         for (String languageTag : supportedLocales) {
397             final Locale supportedLocale = Locale.forLanguageTag(languageTag);
398             // We expect the average length of locale lists used for locale resolution to be
399             // smaller than three, so it's OK to do this as an O(mn) algorithm.
400             final int idx = findFirstMatchIndex(supportedLocale);
401             if (idx == 0) { // We have a match on the first locale, which is good enough
402                 return 0;
403             } else if (idx < bestIndex) {
404                 bestIndex = idx;
405             }
406         }
407         if (bestIndex == Integer.MAX_VALUE) {
408             // no match was found, so we fall back to the first locale in the locale list
409             return 0;
410         } else {
411             return bestIndex;
412         }
413     }
414 
computeFirstMatch(Collection<String> supportedLocales, boolean assumeEnglishIsSupported)415     private Locale computeFirstMatch(Collection<String> supportedLocales,
416             boolean assumeEnglishIsSupported) {
417         int bestIndex = computeFirstMatchIndex(supportedLocales, assumeEnglishIsSupported);
418         return bestIndex == -1 ? null : mList[bestIndex];
419     }
420 
421     /**
422      * Returns the first match in the locale list given an unordered array of supported locales
423      * in BCP 47 format.
424      *
425      * @return The first {@link Locale} from this list that appears in the given array, or
426      *     {@code null} if the {@link LocaleList} is empty.
427      */
428     @Nullable
getFirstMatch(String[] supportedLocales)429     public Locale getFirstMatch(String[] supportedLocales) {
430         return computeFirstMatch(Arrays.asList(supportedLocales),
431                 false /* assume English is not supported */);
432     }
433 
434     /**
435      * {@hide}
436      */
getFirstMatchIndex(String[] supportedLocales)437     public int getFirstMatchIndex(String[] supportedLocales) {
438         return computeFirstMatchIndex(Arrays.asList(supportedLocales),
439                 false /* assume English is not supported */);
440     }
441 
442     /**
443      * Same as getFirstMatch(), but with English assumed to be supported, even if it's not.
444      * {@hide}
445      */
446     @Nullable
getFirstMatchWithEnglishSupported(String[] supportedLocales)447     public Locale getFirstMatchWithEnglishSupported(String[] supportedLocales) {
448         return computeFirstMatch(Arrays.asList(supportedLocales),
449                 true /* assume English is supported */);
450     }
451 
452     /**
453      * {@hide}
454      */
getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales)455     public int getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales) {
456         return computeFirstMatchIndex(supportedLocales, true /* assume English is supported */);
457     }
458 
459     /**
460      * {@hide}
461      */
getFirstMatchIndexWithEnglishSupported(String[] supportedLocales)462     public int getFirstMatchIndexWithEnglishSupported(String[] supportedLocales) {
463         return getFirstMatchIndexWithEnglishSupported(Arrays.asList(supportedLocales));
464     }
465 
466     /**
467      * Returns true if the collection of locale tags only contains empty locales and pseudolocales.
468      * Assumes that there is no repetition in the input.
469      * {@hide}
470      */
isPseudoLocalesOnly(@ullable String[] supportedLocales)471     public static boolean isPseudoLocalesOnly(@Nullable String[] supportedLocales) {
472         if (supportedLocales == null) {
473             return true;
474         }
475 
476         if (supportedLocales.length > NUM_PSEUDO_LOCALES + 1) {
477             // This is for optimization. Since there's no repetition in the input, if we have more
478             // than the number of pseudo-locales plus one for the empty string, it's guaranteed
479             // that we have some meaninful locale in the collection, so the list is not "practically
480             // empty".
481             return false;
482         }
483         for (String locale : supportedLocales) {
484             if (!locale.isEmpty() && !isPseudoLocale(locale)) {
485                 return false;
486             }
487         }
488         return true;
489     }
490 
491     private final static Object sLock = new Object();
492 
493     @GuardedBy("sLock")
494     private static LocaleList sLastExplicitlySetLocaleList = null;
495     @GuardedBy("sLock")
496     private static LocaleList sDefaultLocaleList = null;
497     @GuardedBy("sLock")
498     private static LocaleList sDefaultAdjustedLocaleList = null;
499     @GuardedBy("sLock")
500     private static Locale sLastDefaultLocale = null;
501 
502     /**
503      * The result is guaranteed to include the default Locale returned by Locale.getDefault(), but
504      * not necessarily at the top of the list. The default locale not being at the top of the list
505      * is an indication that the system has set the default locale to one of the user's other
506      * preferred locales, having concluded that the primary preference is not supported but a
507      * secondary preference is.
508      *
509      * <p>Note that the default LocaleList would change if Locale.setDefault() is called. This
510      * method takes that into account by always checking the output of Locale.getDefault() and
511      * recalculating the default LocaleList if needed.</p>
512      */
513     @NonNull @Size(min=1)
getDefault()514     public static LocaleList getDefault() {
515         final Locale defaultLocale = Locale.getDefault();
516         synchronized (sLock) {
517             if (!defaultLocale.equals(sLastDefaultLocale)) {
518                 sLastDefaultLocale = defaultLocale;
519                 // It's either the first time someone has asked for the default locale list, or
520                 // someone has called Locale.setDefault() since we last set or adjusted the default
521                 // locale list. So let's recalculate the locale list.
522                 if (sDefaultLocaleList != null
523                         && defaultLocale.equals(sDefaultLocaleList.get(0))) {
524                     // The default Locale has changed, but it happens to be the first locale in the
525                     // default locale list, so we don't need to construct a new locale list.
526                     return sDefaultLocaleList;
527                 }
528                 sDefaultLocaleList = new LocaleList(defaultLocale, sLastExplicitlySetLocaleList);
529                 sDefaultAdjustedLocaleList = sDefaultLocaleList;
530             }
531             // sDefaultLocaleList can't be null, since it can't be set to null by
532             // LocaleList.setDefault(), and if getDefault() is called before a call to
533             // setDefault(), sLastDefaultLocale would be null and the check above would set
534             // sDefaultLocaleList.
535             return sDefaultLocaleList;
536         }
537     }
538 
539     /**
540      * Returns the default locale list, adjusted by moving the default locale to its first
541      * position.
542      */
543     @NonNull @Size(min=1)
getAdjustedDefault()544     public static LocaleList getAdjustedDefault() {
545         getDefault(); // to recalculate the default locale list, if necessary
546         synchronized (sLock) {
547             return sDefaultAdjustedLocaleList;
548         }
549     }
550 
551     /**
552      * Also sets the default locale by calling Locale.setDefault() with the first locale in the
553      * list.
554      *
555      * @throws NullPointerException if the input is <code>null</code>.
556      * @throws IllegalArgumentException if the input is empty.
557      */
setDefault(@onNull @izemin=1) LocaleList locales)558     public static void setDefault(@NonNull @Size(min=1) LocaleList locales) {
559         setDefault(locales, 0);
560     }
561 
562     /**
563      * This may be used directly by system processes to set the default locale list for apps. For
564      * such uses, the default locale list would always come from the user preferences, but the
565      * default locale may have been chosen to be a locale other than the first locale in the locale
566      * list (based on the locales the app supports).
567      *
568      * {@hide}
569      */
570     @UnsupportedAppUsage
setDefault(@onNull @izemin=1) LocaleList locales, int localeIndex)571     public static void setDefault(@NonNull @Size(min=1) LocaleList locales, int localeIndex) {
572         if (locales == null) {
573             throw new NullPointerException("locales is null");
574         }
575         if (locales.isEmpty()) {
576             throw new IllegalArgumentException("locales is empty");
577         }
578         synchronized (sLock) {
579             sLastDefaultLocale = locales.get(localeIndex);
580             Locale.setDefault(sLastDefaultLocale);
581             sLastExplicitlySetLocaleList = locales;
582             sDefaultLocaleList = locales;
583             if (localeIndex == 0) {
584                 sDefaultAdjustedLocaleList = sDefaultLocaleList;
585             } else {
586                 sDefaultAdjustedLocaleList = new LocaleList(
587                         sLastDefaultLocale, sDefaultLocaleList);
588             }
589         }
590     }
591 }
592