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