blob: ca9cbec99cde511461e8ece1353b2530b87d132b [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;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -080023import android.icu.util.ULocale;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -070024
25import com.android.internal.annotations.GuardedBy;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070026
Roozbeh Pournader834641b2016-01-23 22:34:57 -080027import java.util.Arrays;
28import java.util.Collection;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070029import java.util.HashSet;
30import java.util.Locale;
31
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070032/**
Clara Bayarri66f6bd32016-04-26 12:18:36 +010033 * LocaleList is an immutable list of Locales, typically used to keep an ordered list of user
34 * preferences for locales.
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070035 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -080036public final class LocaleList implements Parcelable {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070037 private final Locale[] mList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -070038 // This is a comma-separated list of the locales in the LocaleList created at construction time,
39 // basically the result of running each locale's toLanguageTag() method and concatenating them
40 // with commas in between.
Yohei Yukawa789d8fd2015-12-03 11:27:05 -080041 @NonNull
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -070042 private final String mStringRepresentation;
43
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070044 private static final Locale[] sEmptyList = new Locale[0];
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -070045 private static final LocaleList sEmptyLocaleList = new LocaleList();
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070046
Clara Bayarri66f6bd32016-04-26 12:18:36 +010047 /**
48 * Retrieves the {@link Locale} at the specified index.
49 *
50 * @param index The position to retrieve.
51 * @return The {@link Locale} in the given index.
52 */
53 public Locale get(int index) {
54 return (0 <= index && index < mList.length) ? mList[index] : null;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070055 }
56
Clara Bayarri66f6bd32016-04-26 12:18:36 +010057 /**
58 * Returns whether the {@link LocaleList} contains no {@link Locale} items.
59 *
60 * @return {@code true} if this {@link LocaleList} has no {@link Locale} items, {@code false}
61 * otherwise.
62 */
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070063 public boolean isEmpty() {
64 return mList.length == 0;
65 }
66
Clara Bayarri66f6bd32016-04-26 12:18:36 +010067 /**
68 * Returns the number of {@link Locale} items in this {@link LocaleList}.
69 */
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -080070 @IntRange(from=0)
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070071 public int size() {
72 return mList.length;
73 }
74
Clara Bayarri66f6bd32016-04-26 12:18:36 +010075 /**
76 * Searches this {@link LocaleList} for the specified {@link Locale} and returns the index of
77 * the first occurrence.
78 *
79 * @param locale The {@link Locale} to search for.
80 * @return The index of the first occurrence of the {@link Locale} or {@code -1} if the item
81 * wasn't found.
82 */
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -080083 @IntRange(from=-1)
84 public int indexOf(Locale locale) {
85 for (int i = 0; i < mList.length; i++) {
86 if (mList[i].equals(locale)) {
87 return i;
88 }
89 }
90 return -1;
91 }
92
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -070093 @Override
94 public boolean equals(Object other) {
95 if (other == this)
96 return true;
97 if (!(other instanceof LocaleList))
98 return false;
99 final Locale[] otherList = ((LocaleList) other).mList;
100 if (mList.length != otherList.length)
101 return false;
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800102 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700103 if (!mList[i].equals(otherList[i]))
104 return false;
105 }
106 return true;
107 }
108
109 @Override
110 public int hashCode() {
111 int result = 1;
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800112 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700113 result = 31 * result + mList[i].hashCode();
114 }
115 return result;
116 }
117
118 @Override
119 public String toString() {
120 StringBuilder sb = new StringBuilder();
121 sb.append("[");
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800122 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700123 sb.append(mList[i]);
124 if (i < mList.length - 1) {
125 sb.append(',');
126 }
127 }
128 sb.append("]");
129 return sb.toString();
130 }
131
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800132 @Override
133 public int describeContents() {
134 return 0;
135 }
136
137 @Override
138 public void writeToParcel(Parcel dest, int parcelableFlags) {
139 dest.writeString(mStringRepresentation);
140 }
141
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100142 /**
143 * Retrieves a String representation of the language tags in this list.
144 */
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700145 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700146 public String toLanguageTags() {
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700147 return mStringRepresentation;
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700148 }
149
150 /**
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100151 * Creates a new {@link LocaleList}.
152 *
153 * <p>For empty lists of {@link Locale} items it is better to use {@link #getEmptyLocaleList()},
154 * which returns a pre-constructed empty list.</p>
155 *
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700156 * @throws NullPointerException if any of the input locales is <code>null</code>.
157 * @throws IllegalArgumentException if any of the input locales repeat.
158 */
Raph Levien10ea92a2016-05-02 12:56:01 -0700159 public LocaleList(@NonNull Locale... list) {
160 if (list.length == 0) {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700161 mList = sEmptyList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700162 mStringRepresentation = "";
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700163 } else {
164 final Locale[] localeList = new Locale[list.length];
165 final HashSet<Locale> seenLocales = new HashSet<Locale>();
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700166 final StringBuilder sb = new StringBuilder();
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800167 for (int i = 0; i < list.length; i++) {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700168 final Locale l = list[i];
169 if (l == null) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800170 throw new NullPointerException("list[" + i + "] is null");
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700171 } else if (seenLocales.contains(l)) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800172 throw new IllegalArgumentException("list[" + i + "] is a repetition");
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700173 } else {
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700174 final Locale localeClone = (Locale) l.clone();
175 localeList[i] = localeClone;
176 sb.append(localeClone.toLanguageTag());
177 if (i < list.length - 1) {
178 sb.append(',');
179 }
180 seenLocales.add(localeClone);
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700181 }
182 }
183 mList = localeList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700184 mStringRepresentation = sb.toString();
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700185 }
186 }
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700187
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800188 /**
189 * Constructs a locale list, with the topLocale moved to the front if it already is
190 * in otherLocales, or added to the front if it isn't.
191 *
192 * {@hide}
193 */
194 public LocaleList(@NonNull Locale topLocale, LocaleList otherLocales) {
195 if (topLocale == null) {
196 throw new NullPointerException("topLocale is null");
197 }
198
199 final int inputLength = (otherLocales == null) ? 0 : otherLocales.mList.length;
200 int topLocaleIndex = -1;
201 for (int i = 0; i < inputLength; i++) {
202 if (topLocale.equals(otherLocales.mList[i])) {
203 topLocaleIndex = i;
204 break;
205 }
206 }
207
208 final int outputLength = inputLength + (topLocaleIndex == -1 ? 1 : 0);
209 final Locale[] localeList = new Locale[outputLength];
210 localeList[0] = (Locale) topLocale.clone();
211 if (topLocaleIndex == -1) {
212 // topLocale was not in otherLocales
213 for (int i = 0; i < inputLength; i++) {
214 localeList[i + 1] = (Locale) otherLocales.mList[i].clone();
215 }
216 } else {
217 for (int i = 0; i < topLocaleIndex; i++) {
218 localeList[i + 1] = (Locale) otherLocales.mList[i].clone();
219 }
220 for (int i = topLocaleIndex + 1; i < inputLength; i++) {
221 localeList[i] = (Locale) otherLocales.mList[i].clone();
222 }
223 }
224
225 final StringBuilder sb = new StringBuilder();
226 for (int i = 0; i < outputLength; i++) {
227 sb.append(localeList[i].toLanguageTag());
228 if (i < outputLength - 1) {
229 sb.append(',');
230 }
231 }
232
233 mList = localeList;
234 mStringRepresentation = sb.toString();
235 }
236
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800237 public static final Parcelable.Creator<LocaleList> CREATOR
238 = new Parcelable.Creator<LocaleList>() {
239 @Override
240 public LocaleList createFromParcel(Parcel source) {
241 return LocaleList.forLanguageTags(source.readString());
242 }
243
244 @Override
245 public LocaleList[] newArray(int size) {
246 return new LocaleList[size];
247 }
248 };
249
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100250 /**
251 * Retrieve an empty instance of {@link LocaleList}.
252 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800253 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700254 public static LocaleList getEmptyLocaleList() {
255 return sEmptyLocaleList;
256 }
257
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100258 /**
259 * Generates a new LocaleList with the given language tags.
260 *
261 * @param list The language tags to be included as a single {@link String} separated by commas.
262 * @return A new instance with the {@link Locale} items identified by the given tags.
263 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800264 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700265 public static LocaleList forLanguageTags(@Nullable String list) {
266 if (list == null || list.equals("")) {
267 return getEmptyLocaleList();
268 } else {
269 final String[] tags = list.split(",");
270 final Locale[] localeArray = new Locale[tags.length];
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800271 for (int i = 0; i < localeArray.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700272 localeArray[i] = Locale.forLanguageTag(tags[i]);
273 }
274 return new LocaleList(localeArray);
275 }
276 }
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700277
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800278 private static String getLikelyScript(Locale locale) {
279 final String script = locale.getScript();
280 if (!script.isEmpty()) {
281 return script;
282 } else {
283 // TODO: Cache the results if this proves to be too slow
284 return ULocale.addLikelySubtags(ULocale.forLocale(locale)).getScript();
285 }
286 }
287
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800288 private static final String STRING_EN_XA = "en-XA";
289 private static final String STRING_AR_XB = "ar-XB";
290 private static final Locale LOCALE_EN_XA = new Locale("en", "XA");
291 private static final Locale LOCALE_AR_XB = new Locale("ar", "XB");
292 private static final int NUM_PSEUDO_LOCALES = 2;
293
294 private static boolean isPseudoLocale(String locale) {
295 return STRING_EN_XA.equals(locale) || STRING_AR_XB.equals(locale);
296 }
297
Igor Viarheichyk025402c2017-10-06 12:46:49 -0700298 /**
299 * Returns true if locale is a pseudo-locale, false otherwise.
300 * {@hide}
301 */
302 public static boolean isPseudoLocale(Locale locale) {
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800303 return LOCALE_EN_XA.equals(locale) || LOCALE_AR_XB.equals(locale);
304 }
305
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800306 @IntRange(from=0, to=1)
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800307 private static int matchScore(Locale supported, Locale desired) {
308 if (supported.equals(desired)) {
309 return 1; // return early so we don't do unnecessary computation
310 }
311 if (!supported.getLanguage().equals(desired.getLanguage())) {
312 return 0;
313 }
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800314 if (isPseudoLocale(supported) || isPseudoLocale(desired)) {
315 // The locales are not the same, but the languages are the same, and one of the locales
316 // is a pseudo-locale. So this is not a match.
317 return 0;
318 }
Roozbeh Pournaderb927c552016-01-15 11:23:42 -0800319 final String supportedScr = getLikelyScript(supported);
320 if (supportedScr.isEmpty()) {
321 // If we can't guess a script, we don't know enough about the locales' language to find
322 // if the locales match. So we fall back to old behavior of matching, which considered
323 // locales with different regions different.
324 final String supportedRegion = supported.getCountry();
325 return (supportedRegion.isEmpty() ||
326 supportedRegion.equals(desired.getCountry()))
327 ? 1 : 0;
328 }
329 final String desiredScr = getLikelyScript(desired);
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800330 // There is no match if the two locales use different scripts. This will most imporantly
331 // take care of traditional vs simplified Chinese.
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800332 return supportedScr.equals(desiredScr) ? 1 : 0;
333 }
334
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800335 private int findFirstMatchIndex(Locale supportedLocale) {
336 for (int idx = 0; idx < mList.length; idx++) {
337 final int score = matchScore(supportedLocale, mList[idx]);
338 if (score > 0) {
339 return idx;
340 }
341 }
342 return Integer.MAX_VALUE;
343 }
344
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800345 private static final Locale EN_LATN = Locale.forLanguageTag("en-Latn");
346
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800347 private int computeFirstMatchIndex(Collection<String> supportedLocales,
348 boolean assumeEnglishIsSupported) {
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800349 if (mList.length == 1) { // just one locale, perhaps the most common scenario
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800350 return 0;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800351 }
352 if (mList.length == 0) { // empty locale list
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800353 return -1;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800354 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800355
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800356 int bestIndex = Integer.MAX_VALUE;
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800357 // Try English first, so we can return early if it's in the LocaleList
358 if (assumeEnglishIsSupported) {
359 final int idx = findFirstMatchIndex(EN_LATN);
360 if (idx == 0) { // We have a match on the first locale, which is good enough
361 return 0;
362 } else if (idx < bestIndex) {
363 bestIndex = idx;
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800364 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800365 }
366 for (String languageTag : supportedLocales) {
367 final Locale supportedLocale = Locale.forLanguageTag(languageTag);
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800368 // We expect the average length of locale lists used for locale resolution to be
369 // smaller than three, so it's OK to do this as an O(mn) algorithm.
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800370 final int idx = findFirstMatchIndex(supportedLocale);
371 if (idx == 0) { // We have a match on the first locale, which is good enough
372 return 0;
373 } else if (idx < bestIndex) {
374 bestIndex = idx;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800375 }
376 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800377 if (bestIndex == Integer.MAX_VALUE) {
378 // no match was found, so we fall back to the first locale in the locale list
379 return 0;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800380 } else {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800381 return bestIndex;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800382 }
Roozbeh Pournader8bca6982015-11-18 17:41:24 -0800383 }
384
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800385 private Locale computeFirstMatch(Collection<String> supportedLocales,
386 boolean assumeEnglishIsSupported) {
387 int bestIndex = computeFirstMatchIndex(supportedLocales, assumeEnglishIsSupported);
388 return bestIndex == -1 ? null : mList[bestIndex];
389 }
390
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800391 /**
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800392 * Returns the first match in the locale list given an unordered array of supported locales
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800393 * in BCP 47 format.
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800394 *
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100395 * @return The first {@link Locale} from this list that appears in the given array, or
396 * {@code null} if the {@link LocaleList} is empty.
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800397 */
398 @Nullable
399 public Locale getFirstMatch(String[] supportedLocales) {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800400 return computeFirstMatch(Arrays.asList(supportedLocales),
401 false /* assume English is not supported */);
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800402 }
403
404 /**
Adam Lesinskib61e4052016-05-19 18:23:05 -0700405 * {@hide}
406 */
407 public int getFirstMatchIndex(String[] supportedLocales) {
408 return computeFirstMatchIndex(Arrays.asList(supportedLocales),
409 false /* assume English is not supported */);
410 }
411
412 /**
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800413 * Same as getFirstMatch(), but with English assumed to be supported, even if it's not.
414 * {@hide}
415 */
416 @Nullable
417 public Locale getFirstMatchWithEnglishSupported(String[] supportedLocales) {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800418 return computeFirstMatch(Arrays.asList(supportedLocales),
419 true /* assume English is supported */);
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800420 }
421
422 /**
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800423 * {@hide}
424 */
425 public int getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales) {
426 return computeFirstMatchIndex(supportedLocales, true /* assume English is supported */);
427 }
428
429 /**
430 * {@hide}
431 */
432 public int getFirstMatchIndexWithEnglishSupported(String[] supportedLocales) {
433 return getFirstMatchIndexWithEnglishSupported(Arrays.asList(supportedLocales));
434 }
435
436 /**
437 * Returns true if the collection of locale tags only contains empty locales and pseudolocales.
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800438 * Assumes that there is no repetition in the input.
439 * {@hide}
440 */
Adam Lesinskib61e4052016-05-19 18:23:05 -0700441 public static boolean isPseudoLocalesOnly(@Nullable String[] supportedLocales) {
442 if (supportedLocales == null) {
443 return true;
444 }
445
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800446 if (supportedLocales.length > NUM_PSEUDO_LOCALES + 1) {
447 // This is for optimization. Since there's no repetition in the input, if we have more
448 // than the number of pseudo-locales plus one for the empty string, it's guaranteed
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800449 // that we have some meaninful locale in the collection, so the list is not "practically
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800450 // empty".
451 return false;
452 }
453 for (String locale : supportedLocales) {
454 if (!locale.isEmpty() && !isPseudoLocale(locale)) {
455 return false;
456 }
457 }
458 return true;
459 }
460
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700461 private final static Object sLock = new Object();
462
463 @GuardedBy("sLock")
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800464 private static LocaleList sLastExplicitlySetLocaleList = null;
465 @GuardedBy("sLock")
466 private static LocaleList sDefaultLocaleList = null;
467 @GuardedBy("sLock")
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800468 private static LocaleList sDefaultAdjustedLocaleList = null;
469 @GuardedBy("sLock")
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800470 private static Locale sLastDefaultLocale = null;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700471
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800472 /**
473 * The result is guaranteed to include the default Locale returned by Locale.getDefault(), but
474 * not necessarily at the top of the list. The default locale not being at the top of the list
475 * is an indication that the system has set the default locale to one of the user's other
476 * preferred locales, having concluded that the primary preference is not supported but a
477 * secondary preference is.
478 *
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100479 * <p>Note that the default LocaleList would change if Locale.setDefault() is called. This
480 * method takes that into account by always checking the output of Locale.getDefault() and
481 * recalculating the default LocaleList if needed.</p>
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800482 */
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700483 @NonNull @Size(min=1)
484 public static LocaleList getDefault() {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800485 final Locale defaultLocale = Locale.getDefault();
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700486 synchronized (sLock) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800487 if (!defaultLocale.equals(sLastDefaultLocale)) {
488 sLastDefaultLocale = defaultLocale;
489 // It's either the first time someone has asked for the default locale list, or
490 // someone has called Locale.setDefault() since we last set or adjusted the default
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800491 // locale list. So let's recalculate the locale list.
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800492 if (sDefaultLocaleList != null
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800493 && defaultLocale.equals(sDefaultLocaleList.get(0))) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800494 // The default Locale has changed, but it happens to be the first locale in the
495 // default locale list, so we don't need to construct a new locale list.
496 return sDefaultLocaleList;
497 }
498 sDefaultLocaleList = new LocaleList(defaultLocale, sLastExplicitlySetLocaleList);
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800499 sDefaultAdjustedLocaleList = sDefaultLocaleList;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700500 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800501 // sDefaultLocaleList can't be null, since it can't be set to null by
502 // LocaleList.setDefault(), and if getDefault() is called before a call to
503 // setDefault(), sLastDefaultLocale would be null and the check above would set
504 // sDefaultLocaleList.
505 return sDefaultLocaleList;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700506 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800507 }
508
509 /**
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800510 * Returns the default locale list, adjusted by moving the default locale to its first
511 * position.
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800512 */
513 @NonNull @Size(min=1)
514 public static LocaleList getAdjustedDefault() {
515 getDefault(); // to recalculate the default locale list, if necessary
516 synchronized (sLock) {
517 return sDefaultAdjustedLocaleList;
518 }
519 }
520
521 /**
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800522 * Also sets the default locale by calling Locale.setDefault() with the first locale in the
523 * list.
524 *
525 * @throws NullPointerException if the input is <code>null</code>.
526 * @throws IllegalArgumentException if the input is empty.
527 */
528 public static void setDefault(@NonNull @Size(min=1) LocaleList locales) {
529 setDefault(locales, 0);
530 }
531
532 /**
533 * This may be used directly by system processes to set the default locale list for apps. For
534 * such uses, the default locale list would always come from the user preferences, but the
535 * default locale may have been chosen to be a locale other than the first locale in the locale
536 * list (based on the locales the app supports).
537 *
538 * {@hide}
539 */
540 public static void setDefault(@NonNull @Size(min=1) LocaleList locales, int localeIndex) {
541 if (locales == null) {
542 throw new NullPointerException("locales is null");
543 }
544 if (locales.isEmpty()) {
545 throw new IllegalArgumentException("locales is empty");
546 }
547 synchronized (sLock) {
548 sLastDefaultLocale = locales.get(localeIndex);
549 Locale.setDefault(sLastDefaultLocale);
550 sLastExplicitlySetLocaleList = locales;
551 sDefaultLocaleList = locales;
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800552 if (localeIndex == 0) {
553 sDefaultAdjustedLocaleList = sDefaultLocaleList;
554 } else {
555 sDefaultAdjustedLocaleList = new LocaleList(
556 sLastDefaultLocale, sDefaultLocaleList);
557 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800558 }
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700559 }
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700560}