Debian Codegraph @

sdk-common/src/main/java/com/android/ide/common/resources/configuration/LocaleQualifier.java

raw
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
17 package com.android.ide.common.resources.configuration;
18
19 import com.android.annotations.NonNull;
20 import com.android.annotations.Nullable;
21 import com.android.annotations.VisibleForTesting;
22 import com.google.common.base.CharMatcher;
23 import com.google.common.base.Splitter;
24
25 import java.util.Iterator;
26 import java.util.Locale;
27
28 /**
29 * A locale qualifier, which can be constructed from:
30 * <ul>
31 * <li>A plain 2-letter language descriptor</li>
32 * <li>A 2-letter language descriptor followed by a -r 2 letter region qualifier</li>
33 * <li>A plain 3-letter language descriptor</li>
34 * <li>A 3-letter language descriptor followed by a -r 2 letter region qualifier</li>
35 * <li>A BCP 47 language tag. The BCP-47 tag uses + instead of - as separators,
36 * and has the prefix b+. Therefore, the BCP-47 tag "zh-Hans-CN" would be
37 * written as "b+zh+Hans+CN" instead.</li>
38 * </ul>
39 */
40 public final class LocaleQualifier extends ResourceQualifier {
41 public static final String FAKE_VALUE = "__"; //$NON-NLS-1$
42 public static final String NAME = "Locale";
43 // TODO: Case insensitive check!
44 public static final String BCP_47_PREFIX = "b+"; //$NON-NLS-1$
45
46 /**
47 * Old historical value for car dock mode that conflicts with the Carib language. The latter is
48 * therefore, excluded from Android.
49 */
50 private static final String CAR_DOCK_MODE = "car";
51
52 @NonNull private String mFull;
53 @NonNull private String mLanguage;
54 @Nullable private String mRegion;
55 @Nullable private String mScript;
56
57 public LocaleQualifier() {
58 mFull = "";
59 }
60
61 public LocaleQualifier(@NonNull String language) {
62 assert language.length() == 2 || language.length() == 3;
63 mLanguage = language;
64 mFull = language;
65 }
66
67 public LocaleQualifier(@Nullable String full, @NonNull String language,
68 @Nullable String region, @Nullable String script) {
69 if (full == null) {
70 if (region != null && region.length() == 3 || script != null) {
71 StringBuilder sb = new StringBuilder(BCP_47_PREFIX);
72 sb.append(language);
73 if (region != null) {
74 sb.append('+');
75 sb.append(region);
76 }
77 if (script != null) {
78 sb.append('+');
79 sb.append(script);
80 }
81 full = sb.toString();
82 } else if (region != null) {
83 full = language + "-r" + region;
84 } else {
85 full = language;
86 }
87 }
88 mFull = full;
89 mLanguage = language;
90 mRegion = region;
91 mScript = script;
92 }
93
94 public static boolean isRegionSegment(@NonNull String segment) {
95 return (segment.startsWith("r") || segment.startsWith("R")) && segment.length() == 3
96 && Character.isLetter(segment.charAt(0)) && Character.isLetter(segment.charAt(1));
97 }
98
99 /**
100 * Checks whether a string is a valid 2 letter language code in ISO 639-1 style.
101 * @param str the string to check
102 * @return is it valid?
103 */
104 private static boolean isValidAlpha2Code(@NonNull String str) {
105 return str.length() == 2 && CharMatcher.JAVA_LETTER.matchesAllOf(str);
106 }
107
108 /**
109 * Checks whether a string is a valid 3 letter language code in ISO 639-2 / ISO 639-5 style.
110 * @param str the string to check
111 * @return is it valid?
112 */
113 private static boolean isValidAlpha3Code(@NonNull String str) {
114 return str.length() == 3 && CharMatcher.JAVA_LETTER.matchesAllOf(str);
115 }
116
117 /**
118 * Checks whether a string is a valid 3 digit in the UN M.49 style.
119 * @param str the string to check
120 * @return is it valid?
121 */
122 private static boolean isValidM49Code(@NonNull String str) {
123 return str.length() == 3 && Character.isDigit(str.charAt(0))
124 && Character.isDigit(str.charAt(1))&& Character.isDigit(str.charAt(2));
125 }
126
127 /**
128 * Creates and returns a qualifier from the given folder segment. If the segment is incorrect,
129 * <code>null</code> is returned.
130 * @param segment the folder segment from which to create a qualifier.
131 * @return a new {@link LocaleQualifier} object or <code>null</code>
132 */
133 @Nullable
134 public static LocaleQualifier getQualifier(@NonNull String segment) {
135 /*
136 * Compute lower case version of the segment.
137 */
138 String segmentLc = segment.toLowerCase(Locale.US);
139
140 /*
141 * Special case: "car" is a valid 3 letter language code (Carib language), but
142 * it conflicts with the (much older) UI mode constant for
143 * car dock mode, so this specific language string should not be recognized
144 * as a 3 letter language string; it should match car dock mode instead.
145 */
146 if (CAR_DOCK_MODE.equals(segment.toLowerCase(Locale.US))) {
147 return null;
148 }
149
150 /*
151 * If segment starts with "b+" then it is a BCP-47 locale.
152 */
153 if (segment.startsWith(BCP_47_PREFIX)) {
154 return parseBcp47(segment);
155 }
156
157 String[] components = segment.split("-");
158 if (components.length > 2) {
159 /*
160 * More than 2 components is not supported. If complex stuff is needed, BCP-47 should
161 * be used instead.
162 */
163 return null;
164 }
165
166 /*
167 * First component: language. Has to be lower case, either 2 character ISO 639-1
168 * or three character ISO 639-2 / ISO 639-5, e.g., en, pt or eng, por...
169 */
170 String language = components[0].toLowerCase(Locale.US);
171 if (!isValidAlpha2Code(language) && !isValidAlpha3Code(language)) {
172 return null;
173 }
174
175 /*
176 * Second component (optional): region. Can be any 2 letters from ISO 3166-1, or 3 digits
177 * from UN M.49. E.g., UK, PT, or 013, 151. The second component must be prefixed with
178 * either lowercase or uppercase "r", so the code would be en-rUK or pt-RPT.
179 */
180 String region = null;
181 if (components.length > 1) {
182 if (components[1].length() < 1
183 || Character.toLowerCase(components[1].charAt(0)) != 'r') {
184 return null;
185 }
186
187 region = components[1].substring(1);
188 if (!isValidAlpha2Code(region) && !isValidM49Code(region)) {
189 return null;
190 }
191 }
192
193 if (region == null) {
194 return new LocaleQualifier(language, language, null, null);
195 } else {
196 return new LocaleQualifier(language + "-r" + region, language, region, null);
197 }
198 }
199
200 /** Given a BCP-47 string, normalizes the case to the recommended casing */
201 @NonNull
202 public static String normalizeCase(@NonNull String segment) {
203 /* According to the BCP-47 spec:
204 o [ISO639-1] recommends that language codes be written in lowercase
205 ('mn' Mongolian).
206
207 o [ISO15924] recommends that script codes use lowercase with the
208 initial letter capitalized ('Cyrl' Cyrillic).
209
210 o [ISO3166-1] recommends that country codes be capitalized ('MN'
211 Mongolia).
212
213
214 An implementation can reproduce this format without accessing the
215 registry as follows. All subtags, including extension and private
216 use subtags, use lowercase letters with two exceptions: two-letter
217 and four-letter subtags that neither appear at the start of the tag
218 nor occur after singletons. Such two-letter subtags are all
219 uppercase (as in the tags "en-CA-x-ca" or "sgn-BE-FR") and four-
220 letter subtags are titlecase (as in the tag "az-Latn-x-latn").
221 */
222 if (isNormalizedCase(segment)) {
223 return segment;
224 }
225
226 StringBuilder sb = new StringBuilder(segment.length());
227 if (segment.startsWith(BCP_47_PREFIX)) {
228 sb.append(BCP_47_PREFIX);
229 assert segment.startsWith(BCP_47_PREFIX);
230 int segmentBegin = BCP_47_PREFIX.length();
231 int segmentLength = segment.length();
232 int start = segmentBegin;
233
234 int lastLength = -1;
235 while (start < segmentLength) {
236 if (start != segmentBegin) {
237 sb.append('+');
238 }
239 int end = segment.indexOf('+', start);
240 if (end == -1) {
241 end = segmentLength;
242 }
243 int length = end - start;
244 if ((length != 2 && length != 4) || start == segmentBegin || lastLength == 1) {
245 for (int i = start; i < end; i++) {
246 sb.append(Character.toLowerCase(segment.charAt(i)));
247 }
248 } else if (length == 2) {
249 for (int i = start; i < end; i++) {
250 sb.append(Character.toUpperCase(segment.charAt(i)));
251 }
252 } else {
253 assert length == 4 : length;
254 sb.append(Character.toUpperCase(segment.charAt(start)));
255 for (int i = start + 1; i < end; i++) {
256 sb.append(Character.toLowerCase(segment.charAt(i)));
257 }
258 }
259
260 lastLength = length;
261 start = end + 1;
262 }
263 } else if (segment.length() == 6) {
264 // Language + region: ll-rRR
265 sb.append(Character.toLowerCase(segment.charAt(0)));
266 sb.append(Character.toLowerCase(segment.charAt(1)));
267 sb.append(segment.charAt(2)); // -
268 sb.append(Character.toLowerCase(segment.charAt(3))); // r
269 sb.append(Character.toUpperCase(segment.charAt(4)));
270 sb.append(Character.toUpperCase(segment.charAt(5)));
271 } else if (segment.length() == 7) {
272 // Language + region: lll-rRR
273 sb.append(Character.toLowerCase(segment.charAt(0)));
274 sb.append(Character.toLowerCase(segment.charAt(1)));
275 sb.append(Character.toLowerCase(segment.charAt(2)));
276 sb.append(segment.charAt(3)); // -
277 sb.append(Character.toLowerCase(segment.charAt(4))); // r
278 sb.append(Character.toUpperCase(segment.charAt(5)));
279 sb.append(Character.toUpperCase(segment.charAt(6)));
280 } else {
281 sb.append(segment.toLowerCase(Locale.US));
282 }
283
284 return sb.toString();
285 }
286
287 /**
288 * Given a BCP-47 string, determines whether the string is already
289 * capitalized correctly (where "correct" means for readability; all strings
290 * should be compared case insensitively)
291 */
292 @VisibleForTesting
293 static boolean isNormalizedCase(@NonNull String segment) {
294 if (segment.startsWith(BCP_47_PREFIX)) {
295 assert segment.startsWith(BCP_47_PREFIX);
296 int segmentBegin = BCP_47_PREFIX.length();
297 int segmentLength = segment.length();
298 int start = segmentBegin;
299
300 int lastLength = -1;
301 while (start < segmentLength) {
302 int end = segment.indexOf('+', start);
303 if (end == -1) {
304 end = segmentLength;
305 }
306 int length = end - start;
307 if ((length != 2 && length != 4) || start == segmentBegin || lastLength == 1) {
308 if (isNotLowerCase(segment, start, end)) {
309 return false;
310 }
311 } else if (length == 2) {
312 if (isNotUpperCase(segment, start, end)) {
313 return false;
314 }
315 } else {
316 assert length == 4 : length;
317 if (isNotUpperCase(segment, start, start + 1)) {
318 return false;
319 }
320 if (isNotLowerCase(segment, start + 1, end)) {
321 return false;
322 }
323 }
324
325 lastLength = length;
326 start = end + 1;
327 }
328
329 return true;
330 } else if (segment.length() == 2) {
331 // Just a language: ll
332 return Character.isLowerCase(segment.charAt(0))
333 && Character.isLowerCase(segment.charAt(1));
334 } else if (segment.length() == 3) {
335 // Just a language: lll
336 return Character.isLowerCase(segment.charAt(0))
337 && Character.isLowerCase(segment.charAt(1))
338 && Character.isLowerCase(segment.charAt(2));
339 } else if (segment.length() == 6) {
340 // Language + region: ll-rRR
341 return Character.isLowerCase(segment.charAt(0))
342 && Character.isLowerCase(segment.charAt(1))
343 && Character.isLowerCase(segment.charAt(3))
344 && Character.isUpperCase(segment.charAt(4))
345 && Character.isUpperCase(segment.charAt(5));
346 } else if (segment.length() == 7) {
347 // Language + region: lll-rRR
348 return Character.isLowerCase(segment.charAt(0))
349 && Character.isLowerCase(segment.charAt(1))
350 && Character.isLowerCase(segment.charAt(2))
351 && Character.isLowerCase(segment.charAt(4))
352 && Character.isUpperCase(segment.charAt(5))
353 && Character.isUpperCase(segment.charAt(6));
354 }
355
356 return true;
357 }
358
359 private static boolean isNotLowerCase(@NonNull String segment, int start, int end) {
360 for (int i = start; i < end; i++) {
361 if (Character.isUpperCase(segment.charAt(i))) {
362 return true;
363 }
364 }
365
366 return false;
367 }
368
369 private static boolean isNotUpperCase(@NonNull String segment, int start, int end) {
370 for (int i = start; i < end; i++) {
371 if (Character.isLowerCase(segment.charAt(i))) {
372 return true;
373 }
374 }
375
376 return false;
377 }
378
379 @NonNull
380 public String getValue() {
381 return mFull;
382 }
383
384 @Override
385 public String getName() {
386 return NAME;
387 }
388
389 @Override
390 public String getShortName() {
391 return NAME;
392 }
393
394 @Override
395 public int since() {
396 // This was added in Lollipop, but you can for example write b+en+US and aapt handles it
397 // compatibly so we don't want to normalize this in normalize() to append -v21 etc
398 return 1;
399 }
400
401 @Override
402 public boolean isValid() {
403 //noinspection StringEquality
404 return mFull != FAKE_VALUE;
405 }
406
407 @Override
408 public boolean hasFakeValue() {
409 //noinspection StringEquality
410 return mFull == FAKE_VALUE;
411 }
412
413 public boolean hasLanguage() {
414 return !FAKE_VALUE.equals(mLanguage);
415 }
416
417 public boolean hasRegion() {
418 return mRegion != null && !FAKE_VALUE.equals(mRegion);
419 }
420
421 @Override
422 public boolean checkAndSet(@NonNull String value, @NonNull FolderConfiguration config) {
423 LocaleQualifier qualifier = getQualifier(value);
424 if (qualifier != null) {
425 config.setLocaleQualifier(qualifier);
426 return true;
427 }
428
429 return false;
430 }
431
432 /**
433 * Used only when constructing the qualifier, don't use after it's been assigned to a
434 * {@link FolderConfiguration}.
435 */
436 void setRegionSegment(@NonNull String segment) {
437 assert segment.length() == 3 : segment;
438 mRegion = new String(new char[] {
439 Character.toUpperCase(segment.charAt(1)),
440 Character.toUpperCase(segment.charAt(2))
441 });
442 mFull = mLanguage + "-r" + mRegion;
443 }
444
445 @SuppressWarnings("RedundantIfStatement")
446 @Override
447 public boolean equals(Object o) {
448 if (this == o) {
449 return true;
450 }
451 if (o == null || getClass() != o.getClass()) {
452 return false;
453 }
454
455 LocaleQualifier qualifier = (LocaleQualifier) o;
456
457 if (!mFull.equals(qualifier.mFull)) {
458 return false;
459 }
460
461 return true;
462 }
463
464 @Override
465 public int hashCode() {
466 return mFull.hashCode();
467 }
468
469 /**
470 * Returns the string used to represent this qualifier in the folder name.
471 */
472 @Override
473 public String getFolderSegment() {
474 return mFull;
475 }
476
477 /** BCP 47 tag or "language,region", or language */
478 @Override
479 public String getShortDisplayValue() {
480 if (mFull.startsWith(BCP_47_PREFIX)) {
481 return mFull;
482 } else if (mRegion != null) {
483 return mLanguage + ',' + mRegion;
484 } else {
485 return mLanguage;
486 }
487 }
488
489 /** Tag: language, or language-region, or BCP-47 tag */
490 public String getTag() {
491 if (mFull.startsWith(BCP_47_PREFIX)) {
492 return mFull.substring(BCP_47_PREFIX.length()).replace('+','-');
493 } else if (mRegion != null) {
494 return mLanguage + '-' + mRegion;
495 } else {
496 return mLanguage;
497 }
498 }
499
500 @Override
501 public String getLongDisplayValue() {
502 if (mFull.startsWith(BCP_47_PREFIX)) {
503 return String.format("Locale %1$s", mFull);
504 } else if (mRegion != null) {
505 return String.format("Locale %1$s_%2$s", mLanguage, mRegion);
506 } else //noinspection StringEquality
507 if (mFull != FAKE_VALUE) {
508 return String.format("Locale %1$s", mLanguage);
509 }
510
511 return ""; //$NON-NLS-1$
512 }
513
514 /**
515 * Parse an Android BCP-47 string (which differs from BCP-47 in that
516 * it has the prefix "b+" and the separator character has been changed from
517 * - to +.
518 *
519 * @param qualifier the folder name to parse
520 * @return a {@linkplain LocaleQualifier} holding the language, region and script
521 * or null if not a valid Android BCP 47 tag
522 */
523 @Nullable
524 public static LocaleQualifier parseBcp47(@NonNull String qualifier) {
525 if (qualifier.startsWith(BCP_47_PREFIX)) {
526 qualifier = normalizeCase(qualifier);
527 Iterator<String> iterator = Splitter.on('+').split(qualifier).iterator();
528 // Skip b+ prefix, already checked above
529 iterator.next();
530
531 if (iterator.hasNext()) {
532 String language = iterator.next();
533 String region = null;
534 String script = null;
535 if (language.length() >= 2 && language.length() <= 3) {
536 if (iterator.hasNext()) {
537 String next = iterator.next();
538 if (next.length() == 4) {
539 // Script specified; look for next
540 script = next;
541 if (iterator.hasNext()) {
542 next = iterator.next();
543 }
544 } else if (next.length() >= 5) {
545 // Past region: specifying a variant
546 return new LocaleQualifier(qualifier, language, null, null);
547 }
548 if (next.length() >= 2 && next.length() <= 3) {
549 region = next;
550 }
551 }
552 if (script == null && (region == null || region.length() == 2)
553 && !iterator.hasNext()) {
554 // Switch from BCP 47 syntax to plain
555 qualifier = language.toLowerCase(Locale.US);
556 if (region != null) {
557 qualifier = qualifier + "-r" + region.toUpperCase(Locale.US);
558 }
559 }
560 return new LocaleQualifier(qualifier, language, region, script);
561 }
562 }
563 }
564
565 return null;
566 }
567
568 @NonNull
569 public String getLanguage() {
570 return mLanguage;
571 }
572
573 @Nullable
574 public String getRegion() {
575 return mRegion;
576 }
577
578 @Nullable
579 public String getScript() {
580 return mScript;
581 }
582
583 @NonNull
584 public String getFull() {
585 return mFull;
586 }
587
588 @Override
589 public boolean isMatchFor(ResourceQualifier qualifier) {
590 if (qualifier instanceof LocaleQualifier) {
591 LocaleQualifier other = (LocaleQualifier)qualifier;
592 if (!mLanguage.equals(other.mLanguage)) {
593 return false;
594 }
595
596 if (mRegion != null && other.mRegion != null && !mRegion.equals(other.mRegion)) {
597 return false;
598 }
599
600 if (mScript != null && other.mScript != null && !mScript.equals(other.mScript)) {
601 return false;
602 }
603
604 return true;
605 }
606 return false;
607 }
608 }