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