[go: nahoru, domu]

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