blob: 0de09efad8eae9212a4bbc4f13601b86029c81cb [file] [log] [blame]
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -07001/*
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
Yohei Yukawa23cbe852016-05-17 16:42:58 -070017package android.os;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070018
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -080019import android.annotation.IntRange;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -070020import android.annotation.NonNull;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070021import android.annotation.Nullable;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -070022import android.annotation.Size;
Andrei Onea24ec3212019-03-15 17:35:05 +000023import android.annotation.UnsupportedAppUsage;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -080024import android.icu.util.ULocale;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -070025
26import com.android.internal.annotations.GuardedBy;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070027
Roozbeh Pournader834641b2016-01-23 22:34:57 -080028import java.util.Arrays;
29import java.util.Collection;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070030import java.util.HashSet;
31import java.util.Locale;
32
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070033/**
Clara Bayarri66f6bd32016-04-26 12:18:36 +010034 * LocaleList is an immutable list of Locales, typically used to keep an ordered list of user
35 * preferences for locales.
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070036 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -080037public final class LocaleList implements Parcelable {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070038 private final Locale[] mList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -070039 // 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.
Yohei Yukawa789d8fd2015-12-03 11:27:05 -080042 @NonNull
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -070043 private final String mStringRepresentation;
44
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070045 private static final Locale[] sEmptyList = new Locale[0];
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -070046 private static final LocaleList sEmptyLocaleList = new LocaleList();
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070047
Clara Bayarri66f6bd32016-04-26 12:18:36 +010048 /**
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 */
54 public Locale get(int index) {
55 return (0 <= index && index < mList.length) ? mList[index] : null;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070056 }
57
Clara Bayarri66f6bd32016-04-26 12:18:36 +010058 /**
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 */
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070064 public boolean isEmpty() {
65 return mList.length == 0;
66 }
67
Clara Bayarri66f6bd32016-04-26 12:18:36 +010068 /**
69 * Returns the number of {@link Locale} items in this {@link LocaleList}.
70 */
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -080071 @IntRange(from=0)
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070072 public int size() {
73 return mList.length;
74 }
75
Clara Bayarri66f6bd32016-04-26 12:18:36 +010076 /**
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 */
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -080084 @IntRange(from=-1)
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
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -070094 @Override
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;
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800103 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700104 if (!mList[i].equals(otherList[i]))
105 return false;
106 }
107 return true;
108 }
109
110 @Override
111 public int hashCode() {
112 int result = 1;
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800113 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700114 result = 31 * result + mList[i].hashCode();
115 }
116 return result;
117 }
118
119 @Override
120 public String toString() {
121 StringBuilder sb = new StringBuilder();
122 sb.append("[");
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800123 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700124 sb.append(mList[i]);
125 if (i < mList.length - 1) {
126 sb.append(',');
127 }
128 }
129 sb.append("]");
130 return sb.toString();
131 }
132
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800133 @Override
134 public int describeContents() {
135 return 0;
136 }
137
138 @Override
139 public void writeToParcel(Parcel dest, int parcelableFlags) {
140 dest.writeString(mStringRepresentation);
141 }
142
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100143 /**
144 * Retrieves a String representation of the language tags in this list.
145 */
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700146 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700147 public String toLanguageTags() {
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700148 return mStringRepresentation;
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700149 }
150
151 /**
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100152 * 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 *
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700157 * @throws NullPointerException if any of the input locales is <code>null</code>.
158 * @throws IllegalArgumentException if any of the input locales repeat.
159 */
Raph Levien10ea92a2016-05-02 12:56:01 -0700160 public LocaleList(@NonNull Locale... list) {
161 if (list.length == 0) {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700162 mList = sEmptyList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700163 mStringRepresentation = "";
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700164 } else {
165 final Locale[] localeList = new Locale[list.length];
166 final HashSet<Locale> seenLocales = new HashSet<Locale>();
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700167 final StringBuilder sb = new StringBuilder();
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800168 for (int i = 0; i < list.length; i++) {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700169 final Locale l = list[i];
170 if (l == null) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800171 throw new NullPointerException("list[" + i + "] is null");
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700172 } else if (seenLocales.contains(l)) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800173 throw new IllegalArgumentException("list[" + i + "] is a repetition");
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700174 } else {
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700175 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);
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700182 }
183 }
184 mList = localeList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700185 mStringRepresentation = sb.toString();
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700186 }
187 }
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700188
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800189 /**
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 */
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
Jeff Sharkey9e8f83d2019-02-28 12:06:45 -0700238 public static final @android.annotation.NonNull Parcelable.Creator<LocaleList> CREATOR
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800239 = 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
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100251 /**
252 * Retrieve an empty instance of {@link LocaleList}.
253 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800254 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700255 public static LocaleList getEmptyLocaleList() {
256 return sEmptyLocaleList;
257 }
258
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100259 /**
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 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800265 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700266 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];
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800272 for (int i = 0; i < localeArray.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700273 localeArray[i] = Locale.forLanguageTag(tags[i]);
274 }
275 return new LocaleList(localeArray);
276 }
277 }
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700278
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800279 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
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800289 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
295 private static boolean isPseudoLocale(String locale) {
296 return STRING_EN_XA.equals(locale) || STRING_AR_XB.equals(locale);
297 }
298
Igor Viarheichyk025402c2017-10-06 12:46:49 -0700299 /**
300 * Returns true if locale is a pseudo-locale, false otherwise.
301 * {@hide}
302 */
303 public static boolean isPseudoLocale(Locale locale) {
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800304 return LOCALE_EN_XA.equals(locale) || LOCALE_AR_XB.equals(locale);
305 }
306
Maurice Lam522ecbe2018-12-04 20:21:40 -0800307 /**
308 * Returns true if locale is a pseudo-locale, false otherwise.
Maurice Lam522ecbe2018-12-04 20:21:40 -0800309 */
Maurice Lam522ecbe2018-12-04 20:21:40 -0800310 public static boolean isPseudoLocale(@Nullable ULocale locale) {
311 return isPseudoLocale(locale != null ? locale.toLocale() : null);
312 }
313
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800314 @IntRange(from=0, to=1)
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800315 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 }
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800322 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 }
Roozbeh Pournaderb927c552016-01-15 11:23:42 -0800327 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);
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800338 // There is no match if the two locales use different scripts. This will most imporantly
339 // take care of traditional vs simplified Chinese.
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800340 return supportedScr.equals(desiredScr) ? 1 : 0;
341 }
342
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800343 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
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800353 private static final Locale EN_LATN = Locale.forLanguageTag("en-Latn");
354
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800355 private int computeFirstMatchIndex(Collection<String> supportedLocales,
356 boolean assumeEnglishIsSupported) {
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800357 if (mList.length == 1) { // just one locale, perhaps the most common scenario
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800358 return 0;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800359 }
360 if (mList.length == 0) { // empty locale list
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800361 return -1;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800362 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800363
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800364 int bestIndex = Integer.MAX_VALUE;
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800365 // 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;
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800372 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800373 }
374 for (String languageTag : supportedLocales) {
375 final Locale supportedLocale = Locale.forLanguageTag(languageTag);
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800376 // 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.
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800378 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;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800383 }
384 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800385 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;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800388 } else {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800389 return bestIndex;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800390 }
Roozbeh Pournader8bca6982015-11-18 17:41:24 -0800391 }
392
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800393 private Locale computeFirstMatch(Collection<String> supportedLocales,
394 boolean assumeEnglishIsSupported) {
395 int bestIndex = computeFirstMatchIndex(supportedLocales, assumeEnglishIsSupported);
396 return bestIndex == -1 ? null : mList[bestIndex];
397 }
398
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800399 /**
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800400 * Returns the first match in the locale list given an unordered array of supported locales
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800401 * in BCP 47 format.
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800402 *
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100403 * @return The first {@link Locale} from this list that appears in the given array, or
404 * {@code null} if the {@link LocaleList} is empty.
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800405 */
406 @Nullable
407 public Locale getFirstMatch(String[] supportedLocales) {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800408 return computeFirstMatch(Arrays.asList(supportedLocales),
409 false /* assume English is not supported */);
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800410 }
411
412 /**
Adam Lesinskib61e4052016-05-19 18:23:05 -0700413 * {@hide}
414 */
415 public int getFirstMatchIndex(String[] supportedLocales) {
416 return computeFirstMatchIndex(Arrays.asList(supportedLocales),
417 false /* assume English is not supported */);
418 }
419
420 /**
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800421 * Same as getFirstMatch(), but with English assumed to be supported, even if it's not.
422 * {@hide}
423 */
424 @Nullable
425 public Locale getFirstMatchWithEnglishSupported(String[] supportedLocales) {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800426 return computeFirstMatch(Arrays.asList(supportedLocales),
427 true /* assume English is supported */);
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800428 }
429
430 /**
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800431 * {@hide}
432 */
433 public int getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales) {
434 return computeFirstMatchIndex(supportedLocales, true /* assume English is supported */);
435 }
436
437 /**
438 * {@hide}
439 */
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.
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800446 * Assumes that there is no repetition in the input.
447 * {@hide}
448 */
Adam Lesinskib61e4052016-05-19 18:23:05 -0700449 public static boolean isPseudoLocalesOnly(@Nullable String[] supportedLocales) {
450 if (supportedLocales == null) {
451 return true;
452 }
453
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800454 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
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800457 // that we have some meaninful locale in the collection, so the list is not "practically
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800458 // 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
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700469 private final static Object sLock = new Object();
470
471 @GuardedBy("sLock")
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800472 private static LocaleList sLastExplicitlySetLocaleList = null;
473 @GuardedBy("sLock")
474 private static LocaleList sDefaultLocaleList = null;
475 @GuardedBy("sLock")
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800476 private static LocaleList sDefaultAdjustedLocaleList = null;
477 @GuardedBy("sLock")
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800478 private static Locale sLastDefaultLocale = null;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700479
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800480 /**
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 *
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100487 * <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>
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800490 */
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700491 @NonNull @Size(min=1)
492 public static LocaleList getDefault() {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800493 final Locale defaultLocale = Locale.getDefault();
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700494 synchronized (sLock) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800495 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
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800499 // locale list. So let's recalculate the locale list.
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800500 if (sDefaultLocaleList != null
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800501 && defaultLocale.equals(sDefaultLocaleList.get(0))) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800502 // 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);
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800507 sDefaultAdjustedLocaleList = sDefaultLocaleList;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700508 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800509 // 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;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700514 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800515 }
516
517 /**
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800518 * Returns the default locale list, adjusted by moving the default locale to its first
519 * position.
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800520 */
521 @NonNull @Size(min=1)
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 /**
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800530 * 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 */
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 */
Andrei Onea24ec3212019-03-15 17:35:05 +0000548 @UnsupportedAppUsage
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800549 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;
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800561 if (localeIndex == 0) {
562 sDefaultAdjustedLocaleList = sDefaultLocaleList;
563 } else {
564 sDefaultAdjustedLocaleList = new LocaleList(
565 sLastDefaultLocale, sDefaultLocaleList);
566 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800567 }
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700568 }
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700569}