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.SuppressLint;
24 import android.compat.annotation.UnsupportedAppUsage;
25 import android.icu.util.ULocale;
26 
27 import com.android.internal.annotations.GuardedBy;
28 
29 import java.util.ArrayList;
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(@ullable Object other)97     public boolean equals(@Nullable 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.writeString8(mStringRepresentation);
143     }
144 
145     /**
146      * Retrieves a String representation of the language tags in this list.
147      */
148     @NonNull
toLanguageTags()149     public String toLanguageTags() {
150         return mStringRepresentation;
151     }
152 
153     /**
154      * Creates a new {@link LocaleList}.
155      *
156      * If two or more same locales are passed, the repeated locales will be dropped.
157      * <p>For empty lists of {@link Locale} items it is better to use {@link #getEmptyLocaleList()},
158      * which returns a pre-constructed empty list.</p>
159      *
160      * @throws NullPointerException if any of the input locales is <code>null</code>.
161      */
LocaleList(@onNull Locale... list)162     public LocaleList(@NonNull Locale... list) {
163         if (list.length == 0) {
164             mList = sEmptyList;
165             mStringRepresentation = "";
166         } else {
167             final ArrayList<Locale> localeList = new ArrayList<>();
168             final HashSet<Locale> seenLocales = new HashSet<Locale>();
169             final StringBuilder sb = new StringBuilder();
170             for (int i = 0; i < list.length; i++) {
171                 final Locale l = list[i];
172                 if (l == null) {
173                     throw new NullPointerException("list[" + i + "] is null");
174                 } else if (seenLocales.contains(l)) {
175                     // Dropping duplicated locale entries.
176                 } else {
177                     final Locale localeClone = (Locale) l.clone();
178                     localeList.add(localeClone);
179                     sb.append(localeClone.toLanguageTag());
180                     if (i < list.length - 1) {
181                         sb.append(',');
182                     }
183                     seenLocales.add(localeClone);
184                 }
185             }
186             mList = localeList.toArray(new Locale[localeList.size()]);
187             mStringRepresentation = sb.toString();
188         }
189     }
190 
191     /**
192      * Constructs a locale list, with the topLocale moved to the front if it already is
193      * in otherLocales, or added to the front if it isn't.
194      *
195      * {@hide}
196      */
LocaleList(@onNull Locale topLocale, LocaleList otherLocales)197     public LocaleList(@NonNull Locale topLocale, LocaleList otherLocales) {
198         if (topLocale == null) {
199             throw new NullPointerException("topLocale is null");
200         }
201 
202         final int inputLength = (otherLocales == null) ? 0 : otherLocales.mList.length;
203         int topLocaleIndex = -1;
204         for (int i = 0; i < inputLength; i++) {
205             if (topLocale.equals(otherLocales.mList[i])) {
206                 topLocaleIndex = i;
207                 break;
208             }
209         }
210 
211         final int outputLength = inputLength + (topLocaleIndex == -1 ? 1 : 0);
212         final Locale[] localeList = new Locale[outputLength];
213         localeList[0] = (Locale) topLocale.clone();
214         if (topLocaleIndex == -1) {
215             // topLocale was not in otherLocales
216             for (int i = 0; i < inputLength; i++) {
217                 localeList[i + 1] = (Locale) otherLocales.mList[i].clone();
218             }
219         } else {
220             for (int i = 0; i < topLocaleIndex; i++) {
221                 localeList[i + 1] = (Locale) otherLocales.mList[i].clone();
222             }
223             for (int i = topLocaleIndex + 1; i < inputLength; i++) {
224                 localeList[i] = (Locale) otherLocales.mList[i].clone();
225             }
226         }
227 
228         final StringBuilder sb = new StringBuilder();
229         for (int i = 0; i < outputLength; i++) {
230             sb.append(localeList[i].toLanguageTag());
231             if (i < outputLength - 1) {
232                 sb.append(',');
233             }
234         }
235 
236         mList = localeList;
237         mStringRepresentation = sb.toString();
238     }
239 
240     public static final @android.annotation.NonNull Parcelable.Creator<LocaleList> CREATOR
241             = new Parcelable.Creator<LocaleList>() {
242         @Override
243         public LocaleList createFromParcel(Parcel source) {
244             return LocaleList.forLanguageTags(source.readString8());
245         }
246 
247         @Override
248         public LocaleList[] newArray(int size) {
249             return new LocaleList[size];
250         }
251     };
252 
253     /**
254      * Retrieve an empty instance of {@link LocaleList}.
255      */
256     @NonNull
getEmptyLocaleList()257     public static LocaleList getEmptyLocaleList() {
258         return sEmptyLocaleList;
259     }
260 
261     /**
262      * Generates a new LocaleList with the given language tags.
263      *
264      * @param list The language tags to be included as a single {@link String} separated by commas.
265      * @return A new instance with the {@link Locale} items identified by the given tags.
266      */
267     @NonNull
forLanguageTags(@ullable String list)268     public static LocaleList forLanguageTags(@Nullable String list) {
269         if (list == null || list.equals("")) {
270             return getEmptyLocaleList();
271         } else {
272             final String[] tags = list.split(",");
273             final Locale[] localeArray = new Locale[tags.length];
274             for (int i = 0; i < localeArray.length; i++) {
275                 localeArray[i] = Locale.forLanguageTag(tags[i]);
276             }
277             return new LocaleList(localeArray);
278         }
279     }
280 
getLikelyScript(Locale locale)281     private static String getLikelyScript(Locale locale) {
282         final String script = locale.getScript();
283         if (!script.isEmpty()) {
284             return script;
285         } else {
286             // TODO: Cache the results if this proves to be too slow
287             return ULocale.addLikelySubtags(ULocale.forLocale(locale)).getScript();
288         }
289     }
290 
291     private static final String STRING_EN_XA = "en-XA";
292     private static final String STRING_AR_XB = "ar-XB";
293     private static final Locale LOCALE_EN_XA = new Locale("en", "XA");
294     private static final Locale LOCALE_AR_XB = new Locale("ar", "XB");
295     private static final int NUM_PSEUDO_LOCALES = 2;
296 
isPseudoLocale(String locale)297     private static boolean isPseudoLocale(String locale) {
298         return STRING_EN_XA.equals(locale) || STRING_AR_XB.equals(locale);
299     }
300 
301     /**
302      * Returns true if locale is a pseudo-locale, false otherwise.
303      * {@hide}
304      */
isPseudoLocale(Locale locale)305     public static boolean isPseudoLocale(Locale locale) {
306         return LOCALE_EN_XA.equals(locale) || LOCALE_AR_XB.equals(locale);
307     }
308 
309     /**
310      * Returns true if locale is a pseudo-locale, false otherwise.
311      */
isPseudoLocale(@ullable ULocale locale)312     public static boolean isPseudoLocale(@Nullable ULocale locale) {
313         return isPseudoLocale(locale != null ? locale.toLocale() : null);
314     }
315 
316     /**
317      * Determine whether two locales are considered a match, even if they are not exactly equal.
318      * They are considered as a match when both of their languages and scripts
319      * (explicit or inferred) are identical. This means that a user would be able to understand
320      * the content written in the supported locale even if they say they prefer the desired locale.
321      *
322      * E.g. [zh-HK] matches [zh-Hant]; [en-US] matches [en-CA]
323      *
324      * @param supported The supported {@link Locale} to be compared.
325      * @param desired   The desired {@link Locale} to be compared.
326      * @return True if they match, false otherwise.
327      */
matchesLanguageAndScript(@uppressLintR) @onNull Locale supported, @SuppressLint(R) @NonNull Locale desired)328     public static boolean matchesLanguageAndScript(@SuppressLint("UseIcu") @NonNull
329             Locale supported, @SuppressLint("UseIcu") @NonNull Locale desired) {
330         if (supported.equals(desired)) {
331             return true;  // return early so we don't do unnecessary computation
332         }
333         if (!supported.getLanguage().equals(desired.getLanguage())) {
334             return false;
335         }
336         if (isPseudoLocale(supported) || isPseudoLocale(desired)) {
337             // The locales are not the same, but the languages are the same, and one of the locales
338             // is a pseudo-locale. So this is not a match.
339             return false;
340         }
341         final String supportedScr = getLikelyScript(supported);
342         if (supportedScr.isEmpty()) {
343             // If we can't guess a script, we don't know enough about the locales' language to find
344             // if the locales match. So we fall back to old behavior of matching, which considered
345             // locales with different regions different.
346             final String supportedRegion = supported.getCountry();
347             return supportedRegion.isEmpty() || supportedRegion.equals(desired.getCountry());
348         }
349         final String desiredScr = getLikelyScript(desired);
350         // There is no match if the two locales use different scripts. This will most imporantly
351         // take care of traditional vs simplified Chinese.
352         return supportedScr.equals(desiredScr);
353     }
354 
findFirstMatchIndex(Locale supportedLocale)355     private int findFirstMatchIndex(Locale supportedLocale) {
356         for (int idx = 0; idx < mList.length; idx++) {
357             if (matchesLanguageAndScript(supportedLocale, mList[idx])) {
358                 return idx;
359             }
360         }
361         return Integer.MAX_VALUE;
362     }
363 
364     private static final Locale EN_LATN = Locale.forLanguageTag("en-Latn");
365 
computeFirstMatchIndex(Collection<String> supportedLocales, boolean assumeEnglishIsSupported)366     private int computeFirstMatchIndex(Collection<String> supportedLocales,
367             boolean assumeEnglishIsSupported) {
368         if (mList.length == 1) {  // just one locale, perhaps the most common scenario
369             return 0;
370         }
371         if (mList.length == 0) {  // empty locale list
372             return -1;
373         }
374 
375         int bestIndex = Integer.MAX_VALUE;
376         // Try English first, so we can return early if it's in the LocaleList
377         if (assumeEnglishIsSupported) {
378             final int idx = findFirstMatchIndex(EN_LATN);
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         for (String languageTag : supportedLocales) {
386             final Locale supportedLocale = Locale.forLanguageTag(languageTag);
387             // We expect the average length of locale lists used for locale resolution to be
388             // smaller than three, so it's OK to do this as an O(mn) algorithm.
389             final int idx = findFirstMatchIndex(supportedLocale);
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         if (bestIndex == Integer.MAX_VALUE) {
397             // no match was found, so we fall back to the first locale in the locale list
398             return 0;
399         } else {
400             return bestIndex;
401         }
402     }
403 
computeFirstMatch(Collection<String> supportedLocales, boolean assumeEnglishIsSupported)404     private Locale computeFirstMatch(Collection<String> supportedLocales,
405             boolean assumeEnglishIsSupported) {
406         int bestIndex = computeFirstMatchIndex(supportedLocales, assumeEnglishIsSupported);
407         return bestIndex == -1 ? null : mList[bestIndex];
408     }
409 
410     /**
411      * Returns the first match in the locale list given an unordered array of supported locales
412      * in BCP 47 format.
413      *
414      * @return The first {@link Locale} from this list that appears in the given array, or
415      *     {@code null} if the {@link LocaleList} is empty.
416      */
417     @Nullable
getFirstMatch(String[] supportedLocales)418     public Locale getFirstMatch(String[] supportedLocales) {
419         return computeFirstMatch(Arrays.asList(supportedLocales),
420                 false /* assume English is not supported */);
421     }
422 
423     /**
424      * {@hide}
425      */
getFirstMatchIndex(String[] supportedLocales)426     public int getFirstMatchIndex(String[] supportedLocales) {
427         return computeFirstMatchIndex(Arrays.asList(supportedLocales),
428                 false /* assume English is not supported */);
429     }
430 
431     /**
432      * Same as getFirstMatch(), but with English assumed to be supported, even if it's not.
433      * {@hide}
434      */
435     @Nullable
getFirstMatchWithEnglishSupported(String[] supportedLocales)436     public Locale getFirstMatchWithEnglishSupported(String[] supportedLocales) {
437         return computeFirstMatch(Arrays.asList(supportedLocales),
438                 true /* assume English is supported */);
439     }
440 
441     /**
442      * {@hide}
443      */
getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales)444     public int getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales) {
445         return computeFirstMatchIndex(supportedLocales, true /* assume English is supported */);
446     }
447 
448     /**
449      * {@hide}
450      */
getFirstMatchIndexWithEnglishSupported(String[] supportedLocales)451     public int getFirstMatchIndexWithEnglishSupported(String[] supportedLocales) {
452         return getFirstMatchIndexWithEnglishSupported(Arrays.asList(supportedLocales));
453     }
454 
455     /**
456      * Returns true if the collection of locale tags only contains empty locales and pseudolocales.
457      * Assumes that there is no repetition in the input.
458      * {@hide}
459      */
isPseudoLocalesOnly(@ullable String[] supportedLocales)460     public static boolean isPseudoLocalesOnly(@Nullable String[] supportedLocales) {
461         if (supportedLocales == null) {
462             return true;
463         }
464 
465         if (supportedLocales.length > NUM_PSEUDO_LOCALES + 1) {
466             // This is for optimization. Since there's no repetition in the input, if we have more
467             // than the number of pseudo-locales plus one for the empty string, it's guaranteed
468             // that we have some meaninful locale in the collection, so the list is not "practically
469             // empty".
470             return false;
471         }
472         for (String locale : supportedLocales) {
473             if (!locale.isEmpty() && !isPseudoLocale(locale)) {
474                 return false;
475             }
476         }
477         return true;
478     }
479 
480     private final static Object sLock = new Object();
481 
482     @GuardedBy("sLock")
483     private static LocaleList sLastExplicitlySetLocaleList = null;
484     @GuardedBy("sLock")
485     private static LocaleList sDefaultLocaleList = null;
486     @GuardedBy("sLock")
487     private static LocaleList sDefaultAdjustedLocaleList = null;
488     @GuardedBy("sLock")
489     private static Locale sLastDefaultLocale = null;
490 
491     /**
492      * The result is guaranteed to include the default Locale returned by Locale.getDefault(), but
493      * not necessarily at the top of the list. The default locale not being at the top of the list
494      * is an indication that the system has set the default locale to one of the user's other
495      * preferred locales, having concluded that the primary preference is not supported but a
496      * secondary preference is.
497      *
498      * <p>Note that the default LocaleList would change if Locale.setDefault() is called. This
499      * method takes that into account by always checking the output of Locale.getDefault() and
500      * recalculating the default LocaleList if needed.</p>
501      */
502     @NonNull @Size(min=1)
getDefault()503     public static LocaleList getDefault() {
504         final Locale defaultLocale = Locale.getDefault();
505         synchronized (sLock) {
506             if (!defaultLocale.equals(sLastDefaultLocale)) {
507                 sLastDefaultLocale = defaultLocale;
508                 // It's either the first time someone has asked for the default locale list, or
509                 // someone has called Locale.setDefault() since we last set or adjusted the default
510                 // locale list. So let's recalculate the locale list.
511                 if (sDefaultLocaleList != null
512                         && defaultLocale.equals(sDefaultLocaleList.get(0))) {
513                     // The default Locale has changed, but it happens to be the first locale in the
514                     // default locale list, so we don't need to construct a new locale list.
515                     return sDefaultLocaleList;
516                 }
517                 sDefaultLocaleList = new LocaleList(defaultLocale, sLastExplicitlySetLocaleList);
518                 sDefaultAdjustedLocaleList = sDefaultLocaleList;
519             }
520             // sDefaultLocaleList can't be null, since it can't be set to null by
521             // LocaleList.setDefault(), and if getDefault() is called before a call to
522             // setDefault(), sLastDefaultLocale would be null and the check above would set
523             // sDefaultLocaleList.
524             return sDefaultLocaleList;
525         }
526     }
527 
528     /**
529      * Returns the default locale list, adjusted by moving the default locale to its first
530      * position.
531      */
532     @NonNull @Size(min=1)
getAdjustedDefault()533     public static LocaleList getAdjustedDefault() {
534         getDefault(); // to recalculate the default locale list, if necessary
535         synchronized (sLock) {
536             return sDefaultAdjustedLocaleList;
537         }
538     }
539 
540     /**
541      * Also sets the default locale by calling Locale.setDefault() with the first locale in the
542      * list.
543      *
544      * @throws NullPointerException if the input is <code>null</code>.
545      * @throws IllegalArgumentException if the input is empty.
546      */
setDefault(@onNull @izemin=1) LocaleList locales)547     public static void setDefault(@NonNull @Size(min=1) LocaleList locales) {
548         setDefault(locales, 0);
549     }
550 
551     /**
552      * This may be used directly by system processes to set the default locale list for apps. For
553      * such uses, the default locale list would always come from the user preferences, but the
554      * default locale may have been chosen to be a locale other than the first locale in the locale
555      * list (based on the locales the app supports).
556      *
557      * {@hide}
558      */
559     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setDefault(@onNull @izemin=1) LocaleList locales, int localeIndex)560     public static void setDefault(@NonNull @Size(min=1) LocaleList locales, int localeIndex) {
561         if (locales == null) {
562             throw new NullPointerException("locales is null");
563         }
564         if (locales.isEmpty()) {
565             throw new IllegalArgumentException("locales is empty");
566         }
567         synchronized (sLock) {
568             sLastDefaultLocale = locales.get(localeIndex);
569             Locale.setDefault(sLastDefaultLocale);
570             sLastExplicitlySetLocaleList = locales;
571             sDefaultLocaleList = locales;
572             if (localeIndex == 0) {
573                 sDefaultAdjustedLocaleList = sDefaultLocaleList;
574             } else {
575                 sDefaultAdjustedLocaleList = new LocaleList(
576                         sLastDefaultLocale, sDefaultLocaleList);
577             }
578         }
579     }
580 }
581