blob: b153e925fbb0fa8bd6a08ca673dc20e7df576c71 [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
17package android.util;
18
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;
Yohei Yukawa789d8fd2015-12-03 11:27:05 -080024import android.os.Parcel;
25import android.os.Parcelable;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -070026
27import com.android.internal.annotations.GuardedBy;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070028
Roozbeh Pournader834641b2016-01-23 22:34:57 -080029import java.util.Arrays;
30import java.util.Collection;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070031import java.util.HashSet;
32import java.util.Locale;
33
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070034/**
Clara Bayarri66f6bd32016-04-26 12:18:36 +010035 * LocaleList is an immutable list of Locales, typically used to keep an ordered list of user
36 * preferences for locales.
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070037 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -080038public final class LocaleList implements Parcelable {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070039 private final Locale[] mList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -070040 // This is a comma-separated list of the locales in the LocaleList created at construction time,
41 // basically the result of running each locale's toLanguageTag() method and concatenating them
42 // with commas in between.
Yohei Yukawa789d8fd2015-12-03 11:27:05 -080043 @NonNull
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -070044 private final String mStringRepresentation;
45
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070046 private static final Locale[] sEmptyList = new Locale[0];
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -070047 private static final LocaleList sEmptyLocaleList = new LocaleList();
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070048
Clara Bayarri66f6bd32016-04-26 12:18:36 +010049 /**
50 * Retrieves the {@link Locale} at the specified index.
51 *
52 * @param index The position to retrieve.
53 * @return The {@link Locale} in the given index.
54 */
55 public Locale get(int index) {
56 return (0 <= index && index < mList.length) ? mList[index] : null;
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070057 }
58
Clara Bayarri66f6bd32016-04-26 12:18:36 +010059 /**
60 * Returns whether the {@link LocaleList} contains no {@link Locale} items.
61 *
62 * @return {@code true} if this {@link LocaleList} has no {@link Locale} items, {@code false}
63 * otherwise.
64 */
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070065 public boolean isEmpty() {
66 return mList.length == 0;
67 }
68
Clara Bayarri66f6bd32016-04-26 12:18:36 +010069 /**
70 * Returns the number of {@link Locale} items in this {@link LocaleList}.
71 */
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -080072 @IntRange(from=0)
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -070073 public int size() {
74 return mList.length;
75 }
76
Clara Bayarri66f6bd32016-04-26 12:18:36 +010077 /**
78 * Searches this {@link LocaleList} for the specified {@link Locale} and returns the index of
79 * the first occurrence.
80 *
81 * @param locale The {@link Locale} to search for.
82 * @return The index of the first occurrence of the {@link Locale} or {@code -1} if the item
83 * wasn't found.
84 */
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -080085 @IntRange(from=-1)
86 public int indexOf(Locale locale) {
87 for (int i = 0; i < mList.length; i++) {
88 if (mList[i].equals(locale)) {
89 return i;
90 }
91 }
92 return -1;
93 }
94
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -070095 @Override
96 public boolean equals(Object other) {
97 if (other == this)
98 return true;
99 if (!(other instanceof LocaleList))
100 return false;
101 final Locale[] otherList = ((LocaleList) other).mList;
102 if (mList.length != otherList.length)
103 return false;
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800104 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700105 if (!mList[i].equals(otherList[i]))
106 return false;
107 }
108 return true;
109 }
110
111 @Override
112 public int hashCode() {
113 int result = 1;
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800114 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700115 result = 31 * result + mList[i].hashCode();
116 }
117 return result;
118 }
119
120 @Override
121 public String toString() {
122 StringBuilder sb = new StringBuilder();
123 sb.append("[");
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800124 for (int i = 0; i < mList.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700125 sb.append(mList[i]);
126 if (i < mList.length - 1) {
127 sb.append(',');
128 }
129 }
130 sb.append("]");
131 return sb.toString();
132 }
133
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800134 @Override
135 public int describeContents() {
136 return 0;
137 }
138
139 @Override
140 public void writeToParcel(Parcel dest, int parcelableFlags) {
141 dest.writeString(mStringRepresentation);
142 }
143
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100144 /**
145 * Retrieves a String representation of the language tags in this list.
146 */
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700147 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700148 public String toLanguageTags() {
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700149 return mStringRepresentation;
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700150 }
151
152 /**
153 * It is almost always better to call {@link #getEmptyLocaleList()} instead which returns
154 * a pre-constructed empty locale list.
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100155 *
156 * @hide
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700157 */
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700158 public LocaleList() {
159 mList = sEmptyList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700160 mStringRepresentation = "";
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700161 }
162
163 /**
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100164 * Creates a new {@link LocaleList}.
165 *
166 * <p>For empty lists of {@link Locale} items it is better to use {@link #getEmptyLocaleList()},
167 * which returns a pre-constructed empty list.</p>
168 *
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700169 * @throws NullPointerException if any of the input locales is <code>null</code>.
170 * @throws IllegalArgumentException if any of the input locales repeat.
171 */
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100172 public LocaleList(@Nullable Locale... list) {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700173 if (list == null || list.length == 0) {
174 mList = sEmptyList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700175 mStringRepresentation = "";
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700176 } else {
177 final Locale[] localeList = new Locale[list.length];
178 final HashSet<Locale> seenLocales = new HashSet<Locale>();
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700179 final StringBuilder sb = new StringBuilder();
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800180 for (int i = 0; i < list.length; i++) {
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700181 final Locale l = list[i];
182 if (l == null) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800183 throw new NullPointerException("list[" + i + "] is null");
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700184 } else if (seenLocales.contains(l)) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800185 throw new IllegalArgumentException("list[" + i + "] is a repetition");
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700186 } else {
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700187 final Locale localeClone = (Locale) l.clone();
188 localeList[i] = localeClone;
189 sb.append(localeClone.toLanguageTag());
190 if (i < list.length - 1) {
191 sb.append(',');
192 }
193 seenLocales.add(localeClone);
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700194 }
195 }
196 mList = localeList;
Roozbeh Pournaderf036ead2015-10-19 16:56:39 -0700197 mStringRepresentation = sb.toString();
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700198 }
199 }
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700200
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800201 /**
202 * Constructs a locale list, with the topLocale moved to the front if it already is
203 * in otherLocales, or added to the front if it isn't.
204 *
205 * {@hide}
206 */
207 public LocaleList(@NonNull Locale topLocale, LocaleList otherLocales) {
208 if (topLocale == null) {
209 throw new NullPointerException("topLocale is null");
210 }
211
212 final int inputLength = (otherLocales == null) ? 0 : otherLocales.mList.length;
213 int topLocaleIndex = -1;
214 for (int i = 0; i < inputLength; i++) {
215 if (topLocale.equals(otherLocales.mList[i])) {
216 topLocaleIndex = i;
217 break;
218 }
219 }
220
221 final int outputLength = inputLength + (topLocaleIndex == -1 ? 1 : 0);
222 final Locale[] localeList = new Locale[outputLength];
223 localeList[0] = (Locale) topLocale.clone();
224 if (topLocaleIndex == -1) {
225 // topLocale was not in otherLocales
226 for (int i = 0; i < inputLength; i++) {
227 localeList[i + 1] = (Locale) otherLocales.mList[i].clone();
228 }
229 } else {
230 for (int i = 0; i < topLocaleIndex; i++) {
231 localeList[i + 1] = (Locale) otherLocales.mList[i].clone();
232 }
233 for (int i = topLocaleIndex + 1; i < inputLength; i++) {
234 localeList[i] = (Locale) otherLocales.mList[i].clone();
235 }
236 }
237
238 final StringBuilder sb = new StringBuilder();
239 for (int i = 0; i < outputLength; i++) {
240 sb.append(localeList[i].toLanguageTag());
241 if (i < outputLength - 1) {
242 sb.append(',');
243 }
244 }
245
246 mList = localeList;
247 mStringRepresentation = sb.toString();
248 }
249
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800250 public static final Parcelable.Creator<LocaleList> CREATOR
251 = new Parcelable.Creator<LocaleList>() {
252 @Override
253 public LocaleList createFromParcel(Parcel source) {
254 return LocaleList.forLanguageTags(source.readString());
255 }
256
257 @Override
258 public LocaleList[] newArray(int size) {
259 return new LocaleList[size];
260 }
261 };
262
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100263 /**
264 * Retrieve an empty instance of {@link LocaleList}.
265 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800266 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700267 public static LocaleList getEmptyLocaleList() {
268 return sEmptyLocaleList;
269 }
270
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100271 /**
272 * Generates a new LocaleList with the given language tags.
273 *
274 * @param list The language tags to be included as a single {@link String} separated by commas.
275 * @return A new instance with the {@link Locale} items identified by the given tags.
276 */
Yohei Yukawa789d8fd2015-12-03 11:27:05 -0800277 @NonNull
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700278 public static LocaleList forLanguageTags(@Nullable String list) {
279 if (list == null || list.equals("")) {
280 return getEmptyLocaleList();
281 } else {
282 final String[] tags = list.split(",");
283 final Locale[] localeArray = new Locale[tags.length];
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800284 for (int i = 0; i < localeArray.length; i++) {
Roozbeh Pournaderb46fdd42015-08-19 14:56:22 -0700285 localeArray[i] = Locale.forLanguageTag(tags[i]);
286 }
287 return new LocaleList(localeArray);
288 }
289 }
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700290
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800291 private static String getLikelyScript(Locale locale) {
292 final String script = locale.getScript();
293 if (!script.isEmpty()) {
294 return script;
295 } else {
296 // TODO: Cache the results if this proves to be too slow
297 return ULocale.addLikelySubtags(ULocale.forLocale(locale)).getScript();
298 }
299 }
300
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800301 private static final String STRING_EN_XA = "en-XA";
302 private static final String STRING_AR_XB = "ar-XB";
303 private static final Locale LOCALE_EN_XA = new Locale("en", "XA");
304 private static final Locale LOCALE_AR_XB = new Locale("ar", "XB");
305 private static final int NUM_PSEUDO_LOCALES = 2;
306
307 private static boolean isPseudoLocale(String locale) {
308 return STRING_EN_XA.equals(locale) || STRING_AR_XB.equals(locale);
309 }
310
311 private static boolean isPseudoLocale(Locale locale) {
312 return LOCALE_EN_XA.equals(locale) || LOCALE_AR_XB.equals(locale);
313 }
314
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800315 @IntRange(from=0, to=1)
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800316 private static int matchScore(Locale supported, Locale desired) {
317 if (supported.equals(desired)) {
318 return 1; // return early so we don't do unnecessary computation
319 }
320 if (!supported.getLanguage().equals(desired.getLanguage())) {
321 return 0;
322 }
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800323 if (isPseudoLocale(supported) || isPseudoLocale(desired)) {
324 // The locales are not the same, but the languages are the same, and one of the locales
325 // is a pseudo-locale. So this is not a match.
326 return 0;
327 }
Roozbeh Pournaderb927c552016-01-15 11:23:42 -0800328 final String supportedScr = getLikelyScript(supported);
329 if (supportedScr.isEmpty()) {
330 // If we can't guess a script, we don't know enough about the locales' language to find
331 // if the locales match. So we fall back to old behavior of matching, which considered
332 // locales with different regions different.
333 final String supportedRegion = supported.getCountry();
334 return (supportedRegion.isEmpty() ||
335 supportedRegion.equals(desired.getCountry()))
336 ? 1 : 0;
337 }
338 final String desiredScr = getLikelyScript(desired);
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800339 // There is no match if the two locales use different scripts. This will most imporantly
340 // take care of traditional vs simplified Chinese.
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800341 return supportedScr.equals(desiredScr) ? 1 : 0;
342 }
343
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800344 private int findFirstMatchIndex(Locale supportedLocale) {
345 for (int idx = 0; idx < mList.length; idx++) {
346 final int score = matchScore(supportedLocale, mList[idx]);
347 if (score > 0) {
348 return idx;
349 }
350 }
351 return Integer.MAX_VALUE;
352 }
353
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800354 private static final Locale EN_LATN = Locale.forLanguageTag("en-Latn");
355
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800356 private int computeFirstMatchIndex(Collection<String> supportedLocales,
357 boolean assumeEnglishIsSupported) {
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800358 if (mList.length == 1) { // just one locale, perhaps the most common scenario
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800359 return 0;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800360 }
361 if (mList.length == 0) { // empty locale list
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800362 return -1;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800363 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800364
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800365 int bestIndex = Integer.MAX_VALUE;
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800366 // Try English first, so we can return early if it's in the LocaleList
367 if (assumeEnglishIsSupported) {
368 final int idx = findFirstMatchIndex(EN_LATN);
369 if (idx == 0) { // We have a match on the first locale, which is good enough
370 return 0;
371 } else if (idx < bestIndex) {
372 bestIndex = idx;
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800373 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800374 }
375 for (String languageTag : supportedLocales) {
376 final Locale supportedLocale = Locale.forLanguageTag(languageTag);
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800377 // We expect the average length of locale lists used for locale resolution to be
378 // smaller than three, so it's OK to do this as an O(mn) algorithm.
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800379 final int idx = findFirstMatchIndex(supportedLocale);
380 if (idx == 0) { // We have a match on the first locale, which is good enough
381 return 0;
382 } else if (idx < bestIndex) {
383 bestIndex = idx;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800384 }
385 }
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800386 if (bestIndex == Integer.MAX_VALUE) {
387 // no match was found, so we fall back to the first locale in the locale list
388 return 0;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800389 } else {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800390 return bestIndex;
Roozbeh Pournader2591cc82015-12-08 22:21:24 -0800391 }
Roozbeh Pournader8bca6982015-11-18 17:41:24 -0800392 }
393
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800394 private Locale computeFirstMatch(Collection<String> supportedLocales,
395 boolean assumeEnglishIsSupported) {
396 int bestIndex = computeFirstMatchIndex(supportedLocales, assumeEnglishIsSupported);
397 return bestIndex == -1 ? null : mList[bestIndex];
398 }
399
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800400 /**
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800401 * Returns the first match in the locale list given an unordered array of supported locales
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800402 * in BCP 47 format.
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800403 *
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100404 * @return The first {@link Locale} from this list that appears in the given array, or
405 * {@code null} if the {@link LocaleList} is empty.
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800406 */
407 @Nullable
408 public Locale getFirstMatch(String[] supportedLocales) {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800409 return computeFirstMatch(Arrays.asList(supportedLocales),
410 false /* assume English is not supported */);
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800411 }
412
413 /**
414 * Same as getFirstMatch(), but with English assumed to be supported, even if it's not.
415 * {@hide}
416 */
417 @Nullable
418 public Locale getFirstMatchWithEnglishSupported(String[] supportedLocales) {
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800419 return computeFirstMatch(Arrays.asList(supportedLocales),
420 true /* assume English is supported */);
Roozbeh Pournaderfb9236c2015-12-15 23:56:11 -0800421 }
422
423 /**
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800424 * {@hide}
425 */
426 public int getFirstMatchIndexWithEnglishSupported(Collection<String> supportedLocales) {
427 return computeFirstMatchIndex(supportedLocales, true /* assume English is supported */);
428 }
429
430 /**
431 * {@hide}
432 */
433 public int getFirstMatchIndexWithEnglishSupported(String[] supportedLocales) {
434 return getFirstMatchIndexWithEnglishSupported(Arrays.asList(supportedLocales));
435 }
436
437 /**
438 * Returns true if the collection of locale tags only contains empty locales and pseudolocales.
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800439 * Assumes that there is no repetition in the input.
440 * {@hide}
441 */
442 public static boolean isPseudoLocalesOnly(String[] supportedLocales) {
443 if (supportedLocales.length > NUM_PSEUDO_LOCALES + 1) {
444 // This is for optimization. Since there's no repetition in the input, if we have more
445 // than the number of pseudo-locales plus one for the empty string, it's guaranteed
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800446 // that we have some meaninful locale in the collection, so the list is not "practically
Roozbeh Pournader1c686f22015-12-18 14:22:14 -0800447 // empty".
448 return false;
449 }
450 for (String locale : supportedLocales) {
451 if (!locale.isEmpty() && !isPseudoLocale(locale)) {
452 return false;
453 }
454 }
455 return true;
456 }
457
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700458 private final static Object sLock = new Object();
459
460 @GuardedBy("sLock")
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800461 private static LocaleList sLastExplicitlySetLocaleList = null;
462 @GuardedBy("sLock")
463 private static LocaleList sDefaultLocaleList = null;
464 @GuardedBy("sLock")
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800465 private static LocaleList sDefaultAdjustedLocaleList = null;
466 @GuardedBy("sLock")
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800467 private static Locale sLastDefaultLocale = null;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700468
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800469 /**
470 * The result is guaranteed to include the default Locale returned by Locale.getDefault(), but
471 * not necessarily at the top of the list. The default locale not being at the top of the list
472 * is an indication that the system has set the default locale to one of the user's other
473 * preferred locales, having concluded that the primary preference is not supported but a
474 * secondary preference is.
475 *
Clara Bayarri66f6bd32016-04-26 12:18:36 +0100476 * <p>Note that the default LocaleList would change if Locale.setDefault() is called. This
477 * method takes that into account by always checking the output of Locale.getDefault() and
478 * recalculating the default LocaleList if needed.</p>
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800479 */
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700480 @NonNull @Size(min=1)
481 public static LocaleList getDefault() {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800482 final Locale defaultLocale = Locale.getDefault();
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700483 synchronized (sLock) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800484 if (!defaultLocale.equals(sLastDefaultLocale)) {
485 sLastDefaultLocale = defaultLocale;
486 // It's either the first time someone has asked for the default locale list, or
487 // someone has called Locale.setDefault() since we last set or adjusted the default
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800488 // locale list. So let's recalculate the locale list.
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800489 if (sDefaultLocaleList != null
Roozbeh Pournaderfee44842016-02-04 15:24:24 -0800490 && defaultLocale.equals(sDefaultLocaleList.get(0))) {
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800491 // The default Locale has changed, but it happens to be the first locale in the
492 // default locale list, so we don't need to construct a new locale list.
493 return sDefaultLocaleList;
494 }
495 sDefaultLocaleList = new LocaleList(defaultLocale, sLastExplicitlySetLocaleList);
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800496 sDefaultAdjustedLocaleList = sDefaultLocaleList;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700497 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800498 // sDefaultLocaleList can't be null, since it can't be set to null by
499 // LocaleList.setDefault(), and if getDefault() is called before a call to
500 // setDefault(), sLastDefaultLocale would be null and the check above would set
501 // sDefaultLocaleList.
502 return sDefaultLocaleList;
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700503 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800504 }
505
506 /**
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800507 * Returns the default locale list, adjusted by moving the default locale to its first
508 * position.
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800509 */
510 @NonNull @Size(min=1)
511 public static LocaleList getAdjustedDefault() {
512 getDefault(); // to recalculate the default locale list, if necessary
513 synchronized (sLock) {
514 return sDefaultAdjustedLocaleList;
515 }
516 }
517
518 /**
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800519 * Also sets the default locale by calling Locale.setDefault() with the first locale in the
520 * list.
521 *
522 * @throws NullPointerException if the input is <code>null</code>.
523 * @throws IllegalArgumentException if the input is empty.
524 */
525 public static void setDefault(@NonNull @Size(min=1) LocaleList locales) {
526 setDefault(locales, 0);
527 }
528
529 /**
530 * This may be used directly by system processes to set the default locale list for apps. For
531 * such uses, the default locale list would always come from the user preferences, but the
532 * default locale may have been chosen to be a locale other than the first locale in the locale
533 * list (based on the locales the app supports).
534 *
535 * {@hide}
536 */
537 public static void setDefault(@NonNull @Size(min=1) LocaleList locales, int localeIndex) {
538 if (locales == null) {
539 throw new NullPointerException("locales is null");
540 }
541 if (locales.isEmpty()) {
542 throw new IllegalArgumentException("locales is empty");
543 }
544 synchronized (sLock) {
545 sLastDefaultLocale = locales.get(localeIndex);
546 Locale.setDefault(sLastDefaultLocale);
547 sLastExplicitlySetLocaleList = locales;
548 sDefaultLocaleList = locales;
Roozbeh Pournader834641b2016-01-23 22:34:57 -0800549 if (localeIndex == 0) {
550 sDefaultAdjustedLocaleList = sDefaultLocaleList;
551 } else {
552 sDefaultAdjustedLocaleList = new LocaleList(
553 sLastDefaultLocale, sDefaultLocaleList);
554 }
Roozbeh Pournader2b5ab182016-01-06 12:22:03 -0800555 }
Roozbeh Pournadera23748a2015-08-31 14:30:36 -0700556 }
Roozbeh Pournader0ba0d6b2015-08-19 11:19:51 -0700557}