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.List;
34 import java.util.Locale;
35 
36 /**
37  * LocaleList is an immutable list of Locales, typically used to keep an ordered list of user
38  * preferences for locales.
39  */
40 public final class LocaleList implements Parcelable {
41     private final Locale[] mList;
42     // This is a comma-separated list of the locales in the LocaleList created at construction time,
43     // basically the result of running each locale's toLanguageTag() method and concatenating them
44     // with commas in between.
45     @NonNull
46     private final String mStringRepresentation;
47 
48     private static final Locale[] sEmptyList = new Locale[0];
49     private static final LocaleList sEmptyLocaleList = new LocaleList();
50 
51     /**
52      * Retrieves the {@link Locale} at the specified index.
53      *
54      * @param index The position to retrieve.
55      * @return The {@link Locale} in the given index.
56      */
get(int index)57     public Locale get(int index) {
58         return (0 <= index && index < mList.length) ? mList[index] : null;
59     }
60 
61     /**
62      * Returns whether the {@link LocaleList} contains no {@link Locale} items.
63      *
64      * @return {@code true} if this {@link LocaleList} has no {@link Locale} items, {@code false}
65      *     otherwise.
66      */
isEmpty()67     public boolean isEmpty() {
68         return mList.length == 0;
69     }
70 
71     /**
72      * Returns the number of {@link Locale} items in this {@link LocaleList}.
73      */
74     @IntRange(from=0)
size()75     public int size() {
76         return mList.length;
77     }
78 
79     /**
80      * Searches this {@link LocaleList} for the specified {@link Locale} and returns the index of
81      * the first occurrence.
82      *
83      * @param locale The {@link Locale} to search for.
84      * @return The index of the first occurrence of the {@link Locale} or {@code -1} if the item
85      *     wasn't found.
86      */
87     @IntRange(from=-1)
indexOf(Locale locale)88     public int indexOf(Locale locale) {
89         for (int i = 0; i < mList.length; i++) {
90             if (mList[i].equals(locale)) {
91                 return i;
92             }
93         }
94         return -1;
95     }
96 
97     @Override
equals(@ullable Object other)98     public boolean equals(@Nullable Object other) {
99         if (other == this)
100             return true;
101         if (!(other instanceof LocaleList))
102             return false;
103         final Locale[] otherList = ((LocaleList) other).mList;
104         if (mList.length != otherList.length)
105             return false;
106         for (int i = 0; i < mList.length; i++) {
107             if (!mList[i].equals(otherList[i]))
108                 return false;
109         }
110         return true;
111     }
112 
113     @Override
hashCode()114     public int hashCode() {
115         int result = 1;
116         for (int i = 0; i < mList.length; i++) {
117             result = 31 * result + mList[i].hashCode();
118         }
119         return result;
120     }
121 
122     @Override
toString()123     public String toString() {
124         StringBuilder sb = new StringBuilder();
125         sb.append("[");
126         for (int i = 0; i < mList.length; i++) {
127             sb.append(mList[i]);
128             if (i < mList.length - 1) {
129                 sb.append(',');
130             }
131         }
132         sb.append("]");
133         return sb.toString();
134     }
135 
136     @Override
describeContents()137     public int describeContents() {
138         return 0;
139     }
140 
141     @Override
writeToParcel(Parcel dest, int parcelableFlags)142     public void writeToParcel(Parcel dest, int parcelableFlags) {
143         dest.writeString8(mStringRepresentation);
144     }
145 
146     /**
147      * Retrieves a String representation of the language tags in this list.
148      */
149     @NonNull
toLanguageTags()150     public String toLanguageTags() {
151         return mStringRepresentation;
152     }
153 
154     /**
155      * Find the intersection between this LocaleList and another
156      * @return an array of the Locales in both LocaleLists
157      * {@hide}
158      */
159     @NonNull
getIntersection(@onNull LocaleList other)160     public Locale[] getIntersection(@NonNull LocaleList other) {
161         List<Locale> intersection = new ArrayList<>();
162         for (Locale l1 : mList) {
163             for (Locale l2 : other.mList) {
164                 if (matchesLanguageAndScript(l2, l1)) {
165                     intersection.add(l1);
166                     break;
167                 }
168             }
169         }
170         return intersection.toArray(new Locale[0]);
171     }
172 
173     /**
174      * Creates a new {@link LocaleList}.
175      *
176      * If two or more same locales are passed, the repeated locales will be dropped.
177      * <p>For empty lists of {@link Locale} items it is better to use {@link #getEmptyLocaleList()},
178      * which returns a pre-constructed empty list.</p>
179      *
180      * @throws NullPointerException if any of the input locales is <code>null</code>.
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 ArrayList<Locale> localeList = new ArrayList<>();
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                     // Dropping duplicated locale entries.
196                 } else {
197                     final Locale localeClone = (Locale) l.clone();
198                     localeList.add(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.toArray(new Locale[localeList.size()]);
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.readString8());
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     /**
337      * Determine whether two locales are considered a match, even if they are not exactly equal.
338      * They are considered as a match when both of their languages and scripts
339      * (explicit or inferred) are identical. This means that a user would be able to understand
340      * the content written in the supported locale even if they say they prefer the desired locale.
341      *
342      * E.g. [zh-HK] matches [zh-Hant]; [en-US] matches [en-CA]
343      *
344      * @param supported The supported {@link Locale} to be compared.
345      * @param desired   The desired {@link Locale} to be compared.
346      * @return True if they match, false otherwise.
347      */
matchesLanguageAndScript(@uppressLint"UseIcu") @onNull Locale supported, @SuppressLint("UseIcu") @NonNull Locale desired)348     public static boolean matchesLanguageAndScript(@SuppressLint("UseIcu") @NonNull
349             Locale supported, @SuppressLint("UseIcu") @NonNull Locale desired) {
350         if (supported.equals(desired)) {
351             return true;  // return early so we don't do unnecessary computation
352         }
353         if (!supported.getLanguage().equals(desired.getLanguage())) {
354             return false;
355         }
356         if (isPseudoLocale(supported) || isPseudoLocale(desired)) {
357             // The locales are not the same, but the languages are the same, and one of the locales
358             // is a pseudo-locale. So this is not a match.
359             return false;
360         }
361         final String supportedScr = getLikelyScript(supported);
362         if (supportedScr.isEmpty()) {
363             // If we can't guess a script, we don't know enough about the locales' language to find
364             // if the locales match. So we fall back to old behavior of matching, which considered
365             // locales with different regions different.
366             final String supportedRegion = supported.getCountry();
367             return supportedRegion.isEmpty() || supportedRegion.equals(desired.getCountry());
368         }
369         final String desiredScr = getLikelyScript(desired);
370         // There is no match if the two locales use different scripts. This will most imporantly
371         // take care of traditional vs simplified Chinese.
372         return supportedScr.equals(desiredScr);
373     }
374 
findFirstMatchIndex(Locale supportedLocale)375     private int findFirstMatchIndex(Locale supportedLocale) {
376         for (int idx = 0; idx < mList.length; idx++) {
377             if (matchesLanguageAndScript(supportedLocale, mList[idx])) {
378                 return idx;
379             }
380         }
381         return Integer.MAX_VALUE;
382     }
383 
384     private static final Locale EN_LATN = Locale.forLanguageTag("en-Latn");
385 
computeFirstMatchIndex(Collection<String> supportedLocales, boolean assumeEnglishIsSupported)386     private int computeFirstMatchIndex(Collection<String> supportedLocales,
387             boolean assumeEnglishIsSupported) {
388         if (mList.length == 1) {  // just one locale, perhaps the most common scenario
389             return 0;
390         }
391         if (mList.length == 0) {  // empty locale list
392             return -1;
393         }
394 
395         int bestIndex = Integer.MAX_VALUE;
396         // Try English first, so we can return early if it's in the LocaleList
397         if (assumeEnglishIsSupported) {
398             final int idx = findFirstMatchIndex(EN_LATN);
399             if (idx == 0) { // We have a match on the first locale, which is good enough
400                 return 0;
401             } else if (idx < bestIndex) {
402                 bestIndex = idx;
403             }
404         }
405         for (String languageTag : supportedLocales) {
406             final Locale supportedLocale = Locale.forLanguageTag(languageTag);
407             // We expect the average length of locale lists used for locale resolution to be
408             // smaller than three, so it's OK to do this as an O(mn) algorithm.
409             final int idx = findFirstMatchIndex(supportedLocale);
410             if (idx == 0) { // We have a match on the first locale, which is good enough
411                 return 0;
412             } else if (idx < bestIndex) {
413                 bestIndex = idx;
414             }
415         }
416         if (bestIndex == Integer.MAX_VALUE) {
417             // no match was found, so we fall back to the first locale in the locale list
418             return 0;
419         } else {
420             return bestIndex;
421         }
422     }
423 
computeFirstMatch(Collection<String> supportedLocales, boolean assumeEnglishIsSupported)424     private Locale computeFirstMatch(Collection<String> supportedLocales,
425             boolean assumeEnglishIsSupported) {
426         int bestIndex = computeFirstMatchIndex(supportedLocales, assumeEnglishIsSupported);
427         return bestIndex == -1 ? null : mList[bestIndex];
428     }
429 
430     /**
431      * Returns the first match in the locale list given an unordered array of supported locales
432      * in BCP 47 format.
433      *
434      * @return The first {@link Locale} from this list that appears in the given array, or
435      *     {@code null} if the {@link LocaleList} is empty.
436      */
437     @Nullable
getFirstMatch(String[] supportedLocales)438     public Locale getFirstMatch(String[] supportedLocales) {
439         return computeFirstMatch(Arrays.asList(supportedLocales),
440                 false /* assume English is not supported */);
441     }
442 
443     /**
444      * {@hide}
445      */
getFirstMatchIndex(String[] supportedLocales)446     public int getFirstMatchIndex(String[] supportedLocales) {
447         return computeFirstMatchIndex(Arrays.asList(supportedLocales),
448                 false /* assume English is not supported */);
449     }
450 
451     /**
452      * Same as getFirstMatch(), but with English assumed to be supported, even if it's not.
453      * {@hide}
454      */
455     @Nullable
getFirstMatchWithEnglishSupported(String[] supportedLocales)456     public Locale getFirstMatchWithEnglishSupported(String[] supportedLocales) {
457         return computeFirstMatch(Arrays.asList(supportedLocales),
458                 true /* assume English is supported */);
459     }
460 
461     /**
462      * {@hide}
463      */
getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales)464     public int getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales) {
465         return computeFirstMatchIndex(supportedLocales, true /* assume English is supported */);
466     }
467 
468     /**
469      * {@hide}
470      */
getFirstMatchIndexWithEnglishSupported(String[] supportedLocales)471     public int getFirstMatchIndexWithEnglishSupported(String[] supportedLocales) {
472         return getFirstMatchIndexWithEnglishSupported(Arrays.asList(supportedLocales));
473     }
474 
475     /**
476      * Returns true if the collection of locale tags only contains empty locales and pseudolocales.
477      * Assumes that there is no repetition in the input.
478      * {@hide}
479      */
isPseudoLocalesOnly(@ullable String[] supportedLocales)480     public static boolean isPseudoLocalesOnly(@Nullable String[] supportedLocales) {
481         if (supportedLocales == null) {
482             return true;
483         }
484 
485         if (supportedLocales.length > NUM_PSEUDO_LOCALES + 1) {
486             // This is for optimization. Since there's no repetition in the input, if we have more
487             // than the number of pseudo-locales plus one for the empty string, it's guaranteed
488             // that we have some meaninful locale in the collection, so the list is not "practically
489             // empty".
490             return false;
491         }
492         for (String locale : supportedLocales) {
493             if (!locale.isEmpty() && !isPseudoLocale(locale)) {
494                 return false;
495             }
496         }
497         return true;
498     }
499 
500     private final static Object sLock = new Object();
501 
502     @GuardedBy("sLock")
503     private static LocaleList sLastExplicitlySetLocaleList = null;
504     @GuardedBy("sLock")
505     private static LocaleList sDefaultLocaleList = null;
506     @GuardedBy("sLock")
507     private static LocaleList sDefaultAdjustedLocaleList = null;
508     @GuardedBy("sLock")
509     private static Locale sLastDefaultLocale = null;
510 
511     /**
512      * The result is guaranteed to include the default Locale returned by Locale.getDefault(), but
513      * not necessarily at the top of the list. The default locale not being at the top of the list
514      * is an indication that the system has set the default locale to one of the user's other
515      * preferred locales, having concluded that the primary preference is not supported but a
516      * secondary preference is.
517      *
518      * <p>Note that the default LocaleList would change if Locale.setDefault() is called. This
519      * method takes that into account by always checking the output of Locale.getDefault() and
520      * recalculating the default LocaleList if needed.</p>
521      */
522     @NonNull @Size(min=1)
getDefault()523     public static LocaleList getDefault() {
524         final Locale defaultLocale = Locale.getDefault();
525         synchronized (sLock) {
526             if (!defaultLocale.equals(sLastDefaultLocale)) {
527                 sLastDefaultLocale = defaultLocale;
528                 // It's either the first time someone has asked for the default locale list, or
529                 // someone has called Locale.setDefault() since we last set or adjusted the default
530                 // locale list. So let's recalculate the locale list.
531                 if (sDefaultLocaleList != null
532                         && defaultLocale.equals(sDefaultLocaleList.get(0))) {
533                     // The default Locale has changed, but it happens to be the first locale in the
534                     // default locale list, so we don't need to construct a new locale list.
535                     return sDefaultLocaleList;
536                 }
537                 sDefaultLocaleList = new LocaleList(defaultLocale, sLastExplicitlySetLocaleList);
538                 sDefaultAdjustedLocaleList = sDefaultLocaleList;
539             }
540             // sDefaultLocaleList can't be null, since it can't be set to null by
541             // LocaleList.setDefault(), and if getDefault() is called before a call to
542             // setDefault(), sLastDefaultLocale would be null and the check above would set
543             // sDefaultLocaleList.
544             return sDefaultLocaleList;
545         }
546     }
547 
548     /**
549      * Returns the default locale list, adjusted by moving the default locale to its first
550      * position.
551      */
552     @NonNull @Size(min=1)
getAdjustedDefault()553     public static LocaleList getAdjustedDefault() {
554         getDefault(); // to recalculate the default locale list, if necessary
555         synchronized (sLock) {
556             return sDefaultAdjustedLocaleList;
557         }
558     }
559 
560     /**
561      * Also sets the default locale by calling Locale.setDefault() with the first locale in the
562      * list.
563      *
564      * @throws NullPointerException if the input is <code>null</code>.
565      * @throws IllegalArgumentException if the input is empty.
566      */
setDefault(@onNull @izemin=1) LocaleList locales)567     public static void setDefault(@NonNull @Size(min=1) LocaleList locales) {
568         setDefault(locales, 0);
569     }
570 
571     /**
572      * This may be used directly by system processes to set the default locale list for apps. For
573      * such uses, the default locale list would always come from the user preferences, but the
574      * default locale may have been chosen to be a locale other than the first locale in the locale
575      * list (based on the locales the app supports).
576      *
577      * {@hide}
578      */
579     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
setDefault(@onNull @izemin=1) LocaleList locales, int localeIndex)580     public static void setDefault(@NonNull @Size(min=1) LocaleList locales, int localeIndex) {
581         if (locales == null) {
582             throw new NullPointerException("locales is null");
583         }
584         if (locales.isEmpty()) {
585             throw new IllegalArgumentException("locales is empty");
586         }
587         synchronized (sLock) {
588             sLastDefaultLocale = locales.get(localeIndex);
589             Locale.setDefault(sLastDefaultLocale);
590             sLastExplicitlySetLocaleList = locales;
591             sDefaultLocaleList = locales;
592             if (localeIndex == 0) {
593                 sDefaultAdjustedLocaleList = sDefaultLocaleList;
594             } else {
595                 sDefaultAdjustedLocaleList = new LocaleList(
596                         sLastDefaultLocale, sDefaultLocaleList);
597             }
598         }
599     }
600 }
601