source: josm/trunk/src/org/openstreetmap/josm/tools/I18n.java@ 16873

Last change on this file since 16873 was 16873, checked in by stoecker, 4 years ago

add sr@latin language, see #18235

  • Property svn:eol-style set to native
File size: 31.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.tools;
3
4import java.io.BufferedInputStream;
5import java.io.File;
6import java.io.IOException;
7import java.io.InputStream;
8import java.lang.annotation.Retention;
9import java.lang.annotation.RetentionPolicy;
10import java.net.URL;
11import java.nio.charset.StandardCharsets;
12import java.nio.file.InvalidPathException;
13import java.text.MessageFormat;
14import java.util.HashMap;
15import java.util.Locale;
16import java.util.Map;
17import java.util.regex.Matcher;
18import java.util.regex.Pattern;
19import java.util.stream.Stream;
20import java.util.zip.ZipEntry;
21import java.util.zip.ZipFile;
22
23import org.openstreetmap.josm.data.osm.TagMap;
24
25/**
26 * Internationalisation support.
27 *
28 * @author Immanuel.Scholz
29 */
30public final class I18n {
31
32 private static final String CORE_TRANS_DIRECTORY = "/data/";
33 private static final String PLUGIN_TRANS_DIRECTORY = "data/";
34
35 /**
36 * This annotates strings which do not permit a clean i18n. This is mostly due to strings
37 * containing two nouns which can occur in singular or plural form.
38 * <br>
39 * No behaviour is associated with this annotation.
40 */
41 @Retention(RetentionPolicy.SOURCE)
42 public @interface QuirkyPluralString {
43 }
44
45 private I18n() {
46 // Hide default constructor for utils classes
47 }
48
49 /**
50 * Enumeration of possible plural modes. It allows us to identify and implement logical conditions of
51 * plural forms defined on <a href="https://help.launchpad.net/Translations/PluralForms">Launchpad</a>.
52 * See <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html">CLDR</a>
53 * for another complete list.
54 * @see #pluralEval
55 */
56 private enum PluralMode {
57 /** Plural = Not 1. This is the default for many languages, including English: 1 day, but 0 days or 2 days. */
58 MODE_NOTONE,
59 /** No plural. Mainly for Asian languages (Indonesian, Chinese, Japanese, ...) */
60 MODE_NONE,
61 /** Plural = Greater than 1. For some latin languages (French, Brazilian Portuguese) */
62 MODE_GREATERONE,
63 /* Special mode for
64 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ar">Arabic</a>.*/
65 MODE_AR,
66 /** Special mode for
67 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#cs">Czech</a>. */
68 MODE_CS,
69 /** Special mode for
70 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#pl">Polish</a>. */
71 MODE_PL,
72 /* Special mode for
73 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ro">Romanian</a>.*
74 MODE_RO,*/
75 /** Special mode for
76 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#lt">Lithuanian</a>. */
77 MODE_LT,
78 /** Special mode for
79 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ru">Russian</a>. */
80 MODE_RU,
81 /** Special mode for
82 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#sk">Slovak</a>. */
83 MODE_SK,
84 /* Special mode for
85 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#sl">Slovenian</a>.*
86 MODE_SL,*/
87 }
88
89 private static volatile PluralMode pluralMode = PluralMode.MODE_NOTONE; /* english default */
90 private static volatile String loadedCode = "en";
91
92 /** Map (english/locale) of singular strings **/
93 private static volatile Map<String, String> strings;
94 /** Map (english/locale) of plural strings **/
95 private static volatile Map<String, String[]> pstrings;
96 private static Locale originalLocale = Locale.getDefault();
97 private static Map<String, PluralMode> languages = new HashMap<>();
98 // NOTE: check also WikiLanguage handling in LanguageInfo.java when adding new languages
99 static {
100 languages.put("ar", PluralMode.MODE_AR);
101 languages.put("ast", PluralMode.MODE_NOTONE);
102 languages.put("bg", PluralMode.MODE_NOTONE);
103 languages.put("be", PluralMode.MODE_RU);
104 languages.put("ca", PluralMode.MODE_NOTONE);
105 languages.put("ca@valencia", PluralMode.MODE_NOTONE);
106 languages.put("cs", PluralMode.MODE_CS);
107 languages.put("da", PluralMode.MODE_NOTONE);
108 languages.put("de", PluralMode.MODE_NOTONE);
109 languages.put("el", PluralMode.MODE_NOTONE);
110 languages.put("en_AU", PluralMode.MODE_NOTONE);
111 //languages.put("en_CA", PluralMode.MODE_NOTONE);
112 languages.put("en_GB", PluralMode.MODE_NOTONE);
113 languages.put("es", PluralMode.MODE_NOTONE);
114 languages.put("et", PluralMode.MODE_NOTONE);
115 //languages.put("eu", PluralMode.MODE_NOTONE);
116 languages.put("fa", PluralMode.MODE_NONE);
117 languages.put("fi", PluralMode.MODE_NOTONE);
118 languages.put("fr", PluralMode.MODE_GREATERONE);
119 languages.put("gl", PluralMode.MODE_NOTONE);
120 //languages.put("he", PluralMode.MODE_NOTONE);
121 languages.put("hu", PluralMode.MODE_NOTONE);
122 languages.put("id", PluralMode.MODE_NONE);
123 languages.put("is", PluralMode.MODE_NOTONE);
124 languages.put("it", PluralMode.MODE_NOTONE);
125 languages.put("ja", PluralMode.MODE_NONE);
126 languages.put("ko", PluralMode.MODE_NONE);
127 languages.put("km", PluralMode.MODE_NONE);
128 languages.put("lt", PluralMode.MODE_LT);
129 languages.put("mr", PluralMode.MODE_NOTONE);
130 languages.put("nb", PluralMode.MODE_NOTONE);
131 languages.put("nl", PluralMode.MODE_NOTONE);
132 languages.put("pl", PluralMode.MODE_PL);
133 languages.put("pt", PluralMode.MODE_NOTONE);
134 languages.put("pt_BR", PluralMode.MODE_GREATERONE);
135 //languages.put("ro", PluralMode.MODE_RO);
136 languages.put("ru", PluralMode.MODE_RU);
137 languages.put("sk", PluralMode.MODE_SK);
138 //languages.put("sl", PluralMode.MODE_SL);
139 languages.put("sr@latin", PluralMode.MODE_RU);
140 languages.put("sv", PluralMode.MODE_NOTONE);
141 //languages.put("tr", PluralMode.MODE_NONE);
142 languages.put("uk", PluralMode.MODE_RU);
143 languages.put("vi", PluralMode.MODE_NONE);
144 languages.put("zh_CN", PluralMode.MODE_NONE);
145 languages.put("zh_TW", PluralMode.MODE_NONE);
146 }
147
148 private static final String HIRAGANA = "hira";
149 private static final String KATAKANA = "kana";
150 private static final String LATIN = "latn";
151 private static final String PINYIN = "pinyin";
152 private static final String ROMAJI = "rm";
153
154 // Matches ISO-639 two and three letters language codes + scripts
155 private static final Pattern LANGUAGE_NAMES = Pattern.compile(
156 "name:(\\p{Lower}{2,3})(?:[-_](?i:(" + String.join("|", HIRAGANA, KATAKANA, LATIN, PINYIN, ROMAJI) + ")))?");
157
158 private static String format(String text, Object... objects) {
159 if (objects.length == 0 && !text.contains("'")) {
160 return text;
161 }
162 try {
163 return MessageFormat.format(text, objects);
164 } catch (InvalidPathException e) {
165 System.err.println("!!! Unable to format '" + text + "': " + e.getMessage());
166 e.printStackTrace();
167 return null;
168 }
169 }
170
171 /**
172 * Translates some text for the current locale.
173 * These strings are collected by a script that runs on the source code files.
174 * After translation, the localizations are distributed with the main program.
175 * <br>
176 * For example, <code>tr("JOSM''s default value is ''{0}''.", val)</code>.
177 * <br>
178 * Use {@link #trn} for distinguishing singular from plural text, i.e.,
179 * do not use {@code tr(size == 1 ? "singular" : "plural")} nor
180 * {@code size == 1 ? tr("singular") : tr("plural")}
181 *
182 * @param text the text to translate.
183 * Must be a string literal. (No constants or local vars.)
184 * Can be broken over multiple lines.
185 * An apostrophe ' must be quoted by another apostrophe.
186 * @param objects the parameters for the string.
187 * Mark occurrences in {@code text} with <code>{0}</code>, <code>{1}</code>, ...
188 * @return the translated string.
189 * @see #trn
190 * @see #trc
191 * @see #trnc
192 */
193 public static String tr(String text, Object... objects) {
194 if (text == null) return null;
195 return format(gettext(text, null), objects);
196 }
197
198 /**
199 * Translates some text in a context for the current locale.
200 * There can be different translations for the same text within different contexts.
201 *
202 * @param context string that helps translators to find an appropriate
203 * translation for {@code text}.
204 * @param text the text to translate.
205 * @return the translated string.
206 * @see #tr
207 * @see #trn
208 * @see #trnc
209 */
210 public static String trc(String context, String text) {
211 if (context == null)
212 return tr(text);
213 if (text == null)
214 return null;
215 return format(gettext(text, context), (Object) null);
216 }
217
218 public static String trcLazy(String context, String text) {
219 if (context == null)
220 return tr(text);
221 if (text == null)
222 return null;
223 return format(gettextLazy(text, context), (Object) null);
224 }
225
226 /**
227 * Marks a string for translation (such that a script can harvest
228 * the translatable strings from the source files).
229 *
230 * For example, <code>
231 * String[] options = new String[] {marktr("up"), marktr("down")};
232 * lbl.setText(tr(options[0]));</code>
233 * @param text the string to be marked for translation.
234 * @return {@code text} unmodified.
235 */
236 public static String marktr(String text) {
237 return text;
238 }
239
240 public static String marktrc(String context, String text) {
241 return text;
242 }
243
244 /**
245 * Translates some text for the current locale and distinguishes between
246 * {@code singularText} and {@code pluralText} depending on {@code n}.
247 * <br>
248 * For instance, {@code trn("There was an error!", "There were errors!", i)} or
249 * <code>trn("Found {0} error in {1}!", "Found {0} errors in {1}!", i, Integer.toString(i), url)</code>.
250 *
251 * @param singularText the singular text to translate.
252 * Must be a string literal. (No constants or local vars.)
253 * Can be broken over multiple lines.
254 * An apostrophe ' must be quoted by another apostrophe.
255 * @param pluralText the plural text to translate.
256 * Must be a string literal. (No constants or local vars.)
257 * Can be broken over multiple lines.
258 * An apostrophe ' must be quoted by another apostrophe.
259 * @param n a number to determine whether {@code singularText} or {@code pluralText} is used.
260 * @param objects the parameters for the string.
261 * Mark occurrences in {@code singularText} and {@code pluralText} with <code>{0}</code>, <code>{1}</code>, ...
262 * @return the translated string.
263 * @see #tr
264 * @see #trc
265 * @see #trnc
266 */
267 public static String trn(String singularText, String pluralText, long n, Object... objects) {
268 return format(gettextn(singularText, pluralText, null, n), objects);
269 }
270
271 /**
272 * Translates some text in a context for the current locale and distinguishes between
273 * {@code singularText} and {@code pluralText} depending on {@code n}.
274 * There can be different translations for the same text within different contexts.
275 *
276 * @param context string that helps translators to find an appropriate
277 * translation for {@code text}.
278 * @param singularText the singular text to translate.
279 * Must be a string literal. (No constants or local vars.)
280 * Can be broken over multiple lines.
281 * An apostrophe ' must be quoted by another apostrophe.
282 * @param pluralText the plural text to translate.
283 * Must be a string literal. (No constants or local vars.)
284 * Can be broken over multiple lines.
285 * An apostrophe ' must be quoted by another apostrophe.
286 * @param n a number to determine whether {@code singularText} or {@code pluralText} is used.
287 * @param objects the parameters for the string.
288 * Mark occurrences in {@code singularText} and {@code pluralText} with <code>{0}</code>, <code>{1}</code>, ...
289 * @return the translated string.
290 * @see #tr
291 * @see #trc
292 * @see #trn
293 */
294 public static String trnc(String context, String singularText, String pluralText, long n, Object... objects) {
295 return format(gettextn(singularText, pluralText, context, n), objects);
296 }
297
298 private static String gettext(String text, String ctx, boolean lazy) {
299 int i;
300 if (ctx == null && text.startsWith("_:") && (i = text.indexOf('\n')) >= 0) {
301 ctx = text.substring(2, i-1);
302 text = text.substring(i+1);
303 }
304 if (strings != null) {
305 String trans = strings.get(ctx == null ? text : "_:"+ctx+'\n'+text);
306 if (trans != null)
307 return trans;
308 }
309 if (pstrings != null) {
310 i = pluralEval(1);
311 String[] trans = pstrings.get(ctx == null ? text : "_:"+ctx+'\n'+text);
312 if (trans != null && trans.length > i)
313 return trans[i];
314 }
315 return lazy ? gettext(text, null) : text;
316 }
317
318 private static String gettext(String text, String ctx) {
319 return gettext(text, ctx, false);
320 }
321
322 /* try without context, when context try fails */
323 private static String gettextLazy(String text, String ctx) {
324 return gettext(text, ctx, true);
325 }
326
327 private static String gettextn(String text, String plural, String ctx, long num) {
328 int i;
329 if (ctx == null && text.startsWith("_:") && (i = text.indexOf('\n')) >= 0) {
330 ctx = text.substring(2, i-1);
331 text = text.substring(i+1);
332 }
333 if (pstrings != null) {
334 i = pluralEval(num);
335 String[] trans = pstrings.get(ctx == null ? text : "_:"+ctx+'\n'+text);
336 if (trans != null && trans.length > i)
337 return trans[i];
338 }
339
340 return num == 1 ? text : plural;
341 }
342
343 /**
344 * Escapes the special i18n characters <code>'{}</code> with quotes.
345 * @param msg unescaped string
346 * @return escaped string
347 * @since 4477
348 */
349 public static String escape(String msg) {
350 if (msg == null) return null;
351 return msg.replace("\'", "\'\'").replace("{", "\'{\'").replace("}", "\'}\'");
352 }
353
354 private static URL getTranslationFile(String lang) {
355 return I18n.class.getResource(CORE_TRANS_DIRECTORY + lang.replace('@', '-') + ".lang");
356 }
357
358 /**
359 * Get a list of all available JOSM Translations.
360 * @return an array of locale objects.
361 */
362 public static Stream<Locale> getAvailableTranslations() {
363 Stream<String> languages = Stream.concat(
364 getTranslationFile("en") != null ? I18n.languages.keySet().stream() : Stream.empty(),
365 Stream.of("en"));
366 return languages.filter(loc -> getTranslationFile(loc) != null).map(LanguageInfo::getLocale);
367 }
368
369 /**
370 * Determines if a language exists for the given code.
371 * @param code The language code
372 * @return {@code true} if a language exists, {@code false} otherwise
373 */
374 public static boolean hasCode(String code) {
375 return languages.containsKey(code);
376 }
377
378 static String setupJavaLocaleProviders() {
379 // Look up SPI providers first (for JosmDecimalFormatSymbolsProvider).
380 // Enable CLDR locale provider on Java 8 to get additional languages, such as Khmer.
381 // https://docs.oracle.com/javase/8/docs/technotes/guides/intl/enhancements.8.html#cldr
382 // FIXME: This must be updated after we switch to Java 9.
383 // See https://docs.oracle.com/javase/9/docs/api/java/util/spi/LocaleServiceProvider.html
384 try {
385 try {
386 // First check we're able to open a stream to our own SPI file
387 // Java will fail on Windows if the jar file is in a folder with a space character!
388 I18n.class.getResourceAsStream("/META-INF/services/java.text.spi.DecimalFormatSymbolsProvider").close();
389 // Don't call Utils.updateSystemProperty to avoid spurious log at startup
390 return System.setProperty("java.locale.providers", "SPI,JRE,CLDR");
391 } catch (RuntimeException | IOException e) {
392 // Don't call Logging class, it may not be fully initialized yet
393 System.err.println("Unable to set SPI locale provider: " + e.getMessage());
394 }
395 } catch (SecurityException e) {
396 // Don't call Logging class, it may not be fully initialized yet
397 System.err.println("Unable to set locale providers: " + e.getMessage());
398 }
399 return System.setProperty("java.locale.providers", "JRE,CLDR");
400 }
401
402 /**
403 * I18n initialization.
404 */
405 public static void init() {
406 setupJavaLocaleProviders();
407
408 /* try initial language settings, may be changed later again */
409 if (!load(LanguageInfo.getJOSMLocaleCode())) {
410 Locale.setDefault(new Locale("en", Locale.getDefault().getCountry()));
411 }
412 }
413
414 /**
415 * I18n initialization for plugins.
416 * @param source file path/name of the JAR or Zip file containing translation strings
417 * @since 4159
418 */
419 public static void addTexts(File source) {
420 if ("en".equals(loadedCode))
421 return;
422 final ZipEntry enfile = new ZipEntry(PLUGIN_TRANS_DIRECTORY + "en.lang");
423 final ZipEntry langfile = new ZipEntry(PLUGIN_TRANS_DIRECTORY + loadedCode + ".lang");
424 try (
425 ZipFile zipFile = new ZipFile(source, StandardCharsets.UTF_8);
426 InputStream orig = zipFile.getInputStream(enfile);
427 InputStream trans = zipFile.getInputStream(langfile)
428 ) {
429 if (orig != null && trans != null)
430 load(orig, trans, true);
431 } catch (IOException | InvalidPathException e) {
432 Logging.trace(e);
433 }
434 }
435
436 private static boolean load(String l) {
437 if ("en".equals(l) || "en_US".equals(l)) {
438 strings = null;
439 pstrings = null;
440 loadedCode = "en";
441 pluralMode = PluralMode.MODE_NOTONE;
442 return true;
443 }
444 URL en = getTranslationFile("en");
445 if (en == null)
446 return false;
447 URL tr = getTranslationFile(l);
448 if (tr == null || !languages.containsKey(l)) {
449 return false;
450 }
451 try (
452 InputStream enStream = Utils.openStream(en);
453 InputStream trStream = Utils.openStream(tr)
454 ) {
455 if (load(enStream, trStream, false)) {
456 pluralMode = languages.get(l);
457 loadedCode = l;
458 return true;
459 }
460 } catch (IOException e) {
461 // Ignore exception
462 Logging.trace(e);
463 }
464 return false;
465 }
466
467 private static boolean load(InputStream en, InputStream tr, boolean add) {
468 Map<String, String> s;
469 Map<String, String[]> p;
470 if (add) {
471 s = strings;
472 p = pstrings;
473 } else {
474 s = new HashMap<>();
475 p = new HashMap<>();
476 }
477 /* file format:
478 Files are always a group. English file and translated file must provide identical datasets.
479
480 for all single strings:
481 {
482 unsigned short (2 byte) stringlength
483 - length 0 indicates missing translation
484 - length 0xFFFE indicates translation equal to original, but otherwise is equal to length 0
485 string
486 }
487 unsigned short (2 byte) 0xFFFF (marks end of single strings)
488 for all multi strings:
489 {
490 unsigned char (1 byte) stringcount
491 - count 0 indicates missing translations
492 - count 0xFE indicates translations equal to original, but otherwise is equal to length 0
493 for stringcount
494 unsigned short (2 byte) stringlength
495 string
496 }
497 */
498 try {
499 InputStream ens = new BufferedInputStream(en);
500 InputStream trs = new BufferedInputStream(tr);
501 byte[] enlen = new byte[2];
502 byte[] trlen = new byte[2];
503 boolean multimode = false;
504 byte[] str = new byte[4096];
505 for (;;) {
506 if (multimode) {
507 int ennum = ens.read();
508 int trnum = trs.read();
509 if (trnum == 0xFE) /* marks identical string, handle equally to non-translated */
510 trnum = 0;
511 if ((ennum == -1 && trnum != -1) || (ennum != -1 && trnum == -1)) /* files do not match */
512 return false;
513 if (ennum == -1) {
514 break;
515 }
516 String[] enstrings = new String[ennum];
517 for (int i = 0; i < ennum; ++i) {
518 int val = ens.read(enlen);
519 if (val != 2) /* file corrupt */
520 return false;
521 val = (enlen[0] < 0 ? 256+enlen[0] : enlen[0])*256+(enlen[1] < 0 ? 256+enlen[1] : enlen[1]);
522 if (val > str.length) {
523 str = new byte[val];
524 }
525 int rval = ens.read(str, 0, val);
526 if (rval != val) /* file corrupt */
527 return false;
528 enstrings[i] = new String(str, 0, val, StandardCharsets.UTF_8);
529 }
530 String[] trstrings = new String[trnum];
531 for (int i = 0; i < trnum; ++i) {
532 int val = trs.read(trlen);
533 if (val != 2) /* file corrupt */
534 return false;
535 val = (trlen[0] < 0 ? 256+trlen[0] : trlen[0])*256+(trlen[1] < 0 ? 256+trlen[1] : trlen[1]);
536 if (val > str.length) {
537 str = new byte[val];
538 }
539 int rval = trs.read(str, 0, val);
540 if (rval != val) /* file corrupt */
541 return false;
542 trstrings[i] = new String(str, 0, val, StandardCharsets.UTF_8);
543 }
544 if (trnum > 0 && !p.containsKey(enstrings[0])) {
545 p.put(enstrings[0], trstrings);
546 }
547 } else {
548 int enval = ens.read(enlen);
549 int trval = trs.read(trlen);
550 if (enval != trval) /* files do not match */
551 return false;
552 if (enval == -1) {
553 break;
554 }
555 if (enval != 2) /* files corrupt */
556 return false;
557 enval = (enlen[0] < 0 ? 256+enlen[0] : enlen[0])*256+(enlen[1] < 0 ? 256+enlen[1] : enlen[1]);
558 trval = (trlen[0] < 0 ? 256+trlen[0] : trlen[0])*256+(trlen[1] < 0 ? 256+trlen[1] : trlen[1]);
559 if (trval == 0xFFFE) /* marks identical string, handle equally to non-translated */
560 trval = 0;
561 if (enval == 0xFFFF) {
562 multimode = true;
563 if (trval != 0xFFFF) /* files do not match */
564 return false;
565 } else {
566 if (enval > str.length) {
567 str = new byte[enval];
568 }
569 if (trval > str.length) {
570 str = new byte[trval];
571 }
572 int val = ens.read(str, 0, enval);
573 if (val != enval) /* file corrupt */
574 return false;
575 String enstr = new String(str, 0, enval, StandardCharsets.UTF_8);
576 if (trval != 0) {
577 val = trs.read(str, 0, trval);
578 if (val != trval) /* file corrupt */
579 return false;
580 String trstr = new String(str, 0, trval, StandardCharsets.UTF_8);
581 if (!s.containsKey(enstr))
582 s.put(enstr, trstr);
583 }
584 }
585 }
586 }
587 } catch (IOException e) {
588 Logging.trace(e);
589 return false;
590 }
591 if (!s.isEmpty()) {
592 strings = s;
593 pstrings = p;
594 return true;
595 }
596 return false;
597 }
598
599 /**
600 * Sets the default locale (see {@link Locale#setDefault(Locale)} to the local
601 * given by <code>localName</code>.
602 *
603 * Ignored if localeName is null. If the locale with name <code>localName</code>
604 * isn't found the default local is set to <code>en</code> (english).
605 *
606 * @param localeName the locale name. Ignored if null.
607 */
608 public static void set(String localeName) {
609 if (localeName != null) {
610 Locale l = LanguageInfo.getLocale(localeName, true);
611 if (load(LanguageInfo.getJOSMLocaleCode(l))) {
612 Locale.setDefault(l);
613 } else {
614 if (!"en".equals(l.getLanguage())) {
615 Logging.info(tr("Unable to find translation for the locale {0}. Reverting to {1}.",
616 LanguageInfo.getDisplayName(l), LanguageInfo.getDisplayName(Locale.getDefault())));
617 } else {
618 strings = null;
619 pstrings = null;
620 }
621 }
622 }
623 }
624
625 /**
626 * Updates the default locale: overrides the numbering system, if defined in internal boundaries.xml for the current language/country.
627 * @since 16109
628 */
629 public static void initializeNumberingFormat() {
630 Locale l = Locale.getDefault();
631 TagMap tags = Territories.getCustomTags(l.getCountry());
632 if (tags != null) {
633 String numberingSystem = tags.get("ldml:nu:" + l.getLanguage());
634 if (numberingSystem != null && !numberingSystem.equals(l.getExtension(Locale.UNICODE_LOCALE_EXTENSION))) {
635 Locale.setDefault(new Locale.Builder()
636 .setLanguage(l.getLanguage())
637 .setRegion(l.getCountry())
638 .setVariant(l.getVariant())
639 .setExtension(Locale.UNICODE_LOCALE_EXTENSION, numberingSystem)
640 .build());
641 }
642 }
643 }
644
645 private static int pluralEval(long n) {
646 switch(pluralMode) {
647 case MODE_NOTONE: /* bg, da, de, el, en, en_AU, en_CA, en_GB, es, et, eu, fi, gl, is, it, iw_IL, mr, nb, nl, sv */
648 return (n != 1) ? 1 : 0;
649 case MODE_NONE: /* id, vi, ja, km, tr, zh_CN, zh_TW */
650 return 0;
651 case MODE_GREATERONE: /* fr, pt_BR */
652 return (n > 1) ? 1 : 0;
653 case MODE_CS:
654 return (n == 1) ? 0 : (((n >= 2) && (n <= 4)) ? 1 : 2);
655 case MODE_AR:
656 return ((n == 0) ? 0 : ((n == 1) ? 1 : ((n == 2) ? 2 : ((((n % 100) >= 3)
657 && ((n % 100) <= 10)) ? 3 : ((((n % 100) >= 11) && ((n % 100) <= 99)) ? 4 : 5)))));
658 case MODE_PL:
659 return (n == 1) ? 0 : (((((n % 10) >= 2) && ((n % 10) <= 4))
660 && (((n % 100) < 10) || ((n % 100) >= 20))) ? 1 : 2);
661 //case MODE_RO:
662 // return ((n == 1) ? 0 : ((((n % 100) > 19) || (((n % 100) == 0) && (n != 0))) ? 2 : 1));
663 case MODE_LT:
664 return ((n % 10) == 1) && ((n % 100) != 11) ? 0 : (((n % 10) >= 2)
665 && (((n % 100) < 10) || ((n % 100) >= 20)) ? 1 : 2);
666 case MODE_RU:
667 return (((n % 10) == 1) && ((n % 100) != 11)) ? 0 : (((((n % 10) >= 2)
668 && ((n % 10) <= 4)) && (((n % 100) < 10) || ((n % 100) >= 20))) ? 1 : 2);
669 case MODE_SK:
670 return (n == 1) ? 1 : (((n >= 2) && (n <= 4)) ? 2 : 0);
671 //case MODE_SL:
672 // return (((n % 100) == 1) ? 1 : (((n % 100) == 2) ? 2 : ((((n % 100) == 3)
673 // || ((n % 100) == 4)) ? 3 : 0)));
674 }
675 return 0;
676 }
677
678 /**
679 * Returns the map of singular translations.
680 * @return the map of singular translations.
681 * @since 13761
682 */
683 public static Map<String, String> getSingularTranslations() {
684 return new HashMap<>(strings);
685 }
686
687 /**
688 * Returns the map of plural translations.
689 * @return the map of plural translations.
690 * @since 13761
691 */
692 public static Map<String, String[]> getPluralTranslations() {
693 return new HashMap<>(pstrings);
694 }
695
696 /**
697 * Returns the original default locale found when the JVM started.
698 * Used to guess real language/country of current user disregarding language chosen in JOSM preferences.
699 * @return the original default locale found when the JVM started
700 * @since 14013
701 */
702 public static Locale getOriginalLocale() {
703 return originalLocale;
704 }
705
706 /**
707 * Returns the localized name of the given script. Only scripts used in the OSM database are known.
708 * @param script Writing system
709 * @return the localized name of the given script, or null
710 * @since 15501
711 */
712 public static String getLocalizedScript(String script) {
713 if (script != null) {
714 switch (script.toLowerCase(Locale.ENGLISH)) {
715 case HIRAGANA:
716 return /* I18n: a Japanese syllabary */ tr("Hiragana");
717 case KATAKANA:
718 return /* I18n: a Japanese syllabary */ tr("Katakana");
719 case LATIN:
720 return /* I18n: usage of latin letters/script for usually non-latin languages */ tr("Latin");
721 case PINYIN:
722 return /* I18n: official romanization system for Standard Chinese */ tr("Pinyin");
723 case ROMAJI:
724 return /* I18n: a Japanese syllabary (latin script) */ tr("Rōmaji");
725 default:
726 Logging.warn("Unsupported script: {0}", script);
727 }
728 }
729 return null;
730 }
731
732 /**
733 * Returns the localized name of the given language and optional script.
734 * @param language Language
735 * @return the pair of localized name + known state of the given language, or null
736 * @since 15501
737 */
738 public static Pair<String, Boolean> getLocalizedLanguageName(String language) {
739 Matcher m = LANGUAGE_NAMES.matcher(language);
740 if (m.matches()) {
741 String code = m.group(1);
742 String label = new Locale(code).getDisplayLanguage();
743 boolean knownNameKey = !code.equals(label);
744 String script = getLocalizedScript(m.group(2));
745 if (script != null) {
746 label += " (" + script + ")";
747 }
748 return new Pair<>(label, knownNameKey);
749 }
750 return null;
751 }
752}
Note: See TracBrowser for help on using the repository browser.