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

Last change on this file since 16049 was 16049, checked in by simon04, 4 years ago

see #18864 - I18n.format: fix strings containing apostrophe U+0027

  • Property svn:eol-style set to native
File size: 30.1 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.ArrayList;
15import java.util.Arrays;
16import java.util.Collection;
17import java.util.Comparator;
18import java.util.HashMap;
19import java.util.Locale;
20import java.util.Map;
21import java.util.regex.Matcher;
22import java.util.regex.Pattern;
23import java.util.zip.ZipEntry;
24import java.util.zip.ZipFile;
25
26/**
27 * Internationalisation support.
28 *
29 * @author Immanuel.Scholz
30 */
31public final class I18n {
32
33 private static final String CORE_TRANS_DIRECTORY = "/data/";
34 private static final String PLUGIN_TRANS_DIRECTORY = "data/";
35
36 /**
37 * This annotates strings which do not permit a clean i18n. This is mostly due to strings
38 * containing two nouns which can occur in singular or plural form.
39 * <br>
40 * No behaviour is associated with this annotation.
41 */
42 @Retention(RetentionPolicy.SOURCE)
43 public @interface QuirkyPluralString {
44 }
45
46 private I18n() {
47 // Hide default constructor for utils classes
48 }
49
50 /**
51 * Enumeration of possible plural modes. It allows us to identify and implement logical conditions of
52 * plural forms defined on <a href="https://help.launchpad.net/Translations/PluralForms">Launchpad</a>.
53 * See <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html">CLDR</a>
54 * for another complete list.
55 * @see #pluralEval
56 */
57 private enum PluralMode {
58 /** Plural = Not 1. This is the default for many languages, including English: 1 day, but 0 days or 2 days. */
59 MODE_NOTONE,
60 /** No plural. Mainly for Asian languages (Indonesian, Chinese, Japanese, ...) */
61 MODE_NONE,
62 /** Plural = Greater than 1. For some latin languages (French, Brazilian Portuguese) */
63 MODE_GREATERONE,
64 /* Special mode for
65 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ar">Arabic</a>.*/
66 MODE_AR,
67 /** Special mode for
68 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#cs">Czech</a>. */
69 MODE_CS,
70 /** Special mode for
71 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#pl">Polish</a>. */
72 MODE_PL,
73 /* Special mode for
74 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ro">Romanian</a>.*
75 MODE_RO,*/
76 /** Special mode for
77 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#lt">Lithuanian</a>. */
78 MODE_LT,
79 /** Special mode for
80 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#ru">Russian</a>. */
81 MODE_RU,
82 /** Special mode for
83 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#sk">Slovak</a>. */
84 MODE_SK,
85 /* Special mode for
86 * <a href="http://www.unicode.org/cldr/charts/latest/supplemental/language_plural_rules.html#sl">Slovenian</a>.*
87 MODE_SL,*/
88 }
89
90 private static volatile PluralMode pluralMode = PluralMode.MODE_NOTONE; /* english default */
91 private static volatile String loadedCode = "en";
92
93 /** Map (english/locale) of singular strings **/
94 private static volatile Map<String, String> strings;
95 /** Map (english/locale) of plural strings **/
96 private static volatile Map<String, String[]> pstrings;
97 private static Locale originalLocale = Locale.getDefault();
98 private static Map<String, PluralMode> languages = new HashMap<>();
99 // NOTE: check also WikiLanguage handling in LanguageInfo.java when adding new languages
100 static {
101 languages.put("ar", PluralMode.MODE_AR);
102 languages.put("ast", PluralMode.MODE_NOTONE);
103 languages.put("bg", PluralMode.MODE_NOTONE);
104 languages.put("be", PluralMode.MODE_RU);
105 languages.put("ca", PluralMode.MODE_NOTONE);
106 languages.put("ca@valencia", PluralMode.MODE_NOTONE);
107 languages.put("cs", PluralMode.MODE_CS);
108 languages.put("da", PluralMode.MODE_NOTONE);
109 languages.put("de", PluralMode.MODE_NOTONE);
110 languages.put("el", PluralMode.MODE_NOTONE);
111 languages.put("en_AU", PluralMode.MODE_NOTONE);
112 //languages.put("en_CA", PluralMode.MODE_NOTONE);
113 languages.put("en_GB", PluralMode.MODE_NOTONE);
114 languages.put("es", PluralMode.MODE_NOTONE);
115 languages.put("et", PluralMode.MODE_NOTONE);
116 //languages.put("eu", PluralMode.MODE_NOTONE);
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 // fully supported only with Java 8 and later (needs CLDR)
128 languages.put("km", PluralMode.MODE_NONE);
129 languages.put("lt", PluralMode.MODE_LT);
130 languages.put("mr", PluralMode.MODE_NOTONE);
131 languages.put("nb", PluralMode.MODE_NOTONE);
132 languages.put("nl", PluralMode.MODE_NOTONE);
133 languages.put("pl", PluralMode.MODE_PL);
134 languages.put("pt", PluralMode.MODE_NOTONE);
135 languages.put("pt_BR", PluralMode.MODE_GREATERONE);
136 //languages.put("ro", PluralMode.MODE_RO);
137 languages.put("ru", PluralMode.MODE_RU);
138 languages.put("sk", PluralMode.MODE_SK);
139 //languages.put("sl", PluralMode.MODE_SL);
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 public static String escape(String msg) {
344 if (msg == null) return null;
345 return msg.replace("\'", "\'\'").replace("{", "\'{\'").replace("}", "\'}\'");
346 }
347
348 private static URL getTranslationFile(String lang) {
349 return I18n.class.getResource(CORE_TRANS_DIRECTORY + lang.replace('@', '-') + ".lang");
350 }
351
352 /**
353 * Get a list of all available JOSM Translations.
354 * @return an array of locale objects.
355 */
356 public static Locale[] getAvailableTranslations() {
357 Collection<Locale> v = new ArrayList<>(languages.size());
358 if (getTranslationFile("en") != null) {
359 for (String loc : languages.keySet()) {
360 if (getTranslationFile(loc) != null) {
361 v.add(LanguageInfo.getLocale(loc));
362 }
363 }
364 }
365 v.add(Locale.ENGLISH);
366 Locale[] l = new Locale[v.size()];
367 l = v.toArray(l);
368 Arrays.sort(l, Comparator.comparing(Locale::toString));
369 return l;
370 }
371
372 /**
373 * Determines if a language exists for the given code.
374 * @param code The language code
375 * @return {@code true} if a language exists, {@code false} otherwise
376 */
377 public static boolean hasCode(String code) {
378 return languages.containsKey(code);
379 }
380
381 static String setupJavaLocaleProviders() {
382 // Look up SPI providers first (for JosmDecimalFormatSymbolsProvider).
383 // Enable CLDR locale provider on Java 8 to get additional languages, such as Khmer.
384 // https://docs.oracle.com/javase/8/docs/technotes/guides/intl/enhancements.8.html#cldr
385 // FIXME: This must be updated after we switch to Java 9.
386 // See https://docs.oracle.com/javase/9/docs/api/java/util/spi/LocaleServiceProvider.html
387 try {
388 try {
389 // First check we're able to open a stream to our own SPI file
390 // Java will fail on Windows if the jar file is in a folder with a space character!
391 I18n.class.getResourceAsStream("/META-INF/services/java.text.spi.DecimalFormatSymbolsProvider").close();
392 // Don't call Utils.updateSystemProperty to avoid spurious log at startup
393 return System.setProperty("java.locale.providers", "SPI,JRE,CLDR");
394 } catch (RuntimeException | IOException e) {
395 // Don't call Logging class, it may not be fully initialized yet
396 System.err.println("Unable to set SPI locale provider: " + e.getMessage());
397 }
398 } catch (SecurityException e) {
399 // Don't call Logging class, it may not be fully initialized yet
400 System.err.println("Unable to set locale providers: " + e.getMessage());
401 }
402 return System.setProperty("java.locale.providers", "JRE,CLDR");
403 }
404
405 /**
406 * I18n initialization.
407 */
408 public static void init() {
409 setupJavaLocaleProviders();
410
411 /* try initial language settings, may be changed later again */
412 if (!load(LanguageInfo.getJOSMLocaleCode())) {
413 Locale.setDefault(new Locale("en", Locale.getDefault().getCountry()));
414 }
415 }
416
417 /**
418 * I18n initialization for plugins.
419 * @param source file path/name of the JAR or Zip file containing translation strings
420 * @since 4159
421 */
422 public static void addTexts(File source) {
423 if ("en".equals(loadedCode))
424 return;
425 final ZipEntry enfile = new ZipEntry(PLUGIN_TRANS_DIRECTORY + "en.lang");
426 final ZipEntry langfile = new ZipEntry(PLUGIN_TRANS_DIRECTORY + loadedCode + ".lang");
427 try (
428 ZipFile zipFile = new ZipFile(source, StandardCharsets.UTF_8);
429 InputStream orig = zipFile.getInputStream(enfile);
430 InputStream trans = zipFile.getInputStream(langfile)
431 ) {
432 if (orig != null && trans != null)
433 load(orig, trans, true);
434 } catch (IOException | InvalidPathException e) {
435 Logging.trace(e);
436 }
437 }
438
439 private static boolean load(String l) {
440 if ("en".equals(l) || "en_US".equals(l)) {
441 strings = null;
442 pstrings = null;
443 loadedCode = "en";
444 pluralMode = PluralMode.MODE_NOTONE;
445 return true;
446 }
447 URL en = getTranslationFile("en");
448 if (en == null)
449 return false;
450 URL tr = getTranslationFile(l);
451 if (tr == null || !languages.containsKey(l)) {
452 return false;
453 }
454 try (
455 InputStream enStream = Utils.openStream(en);
456 InputStream trStream = Utils.openStream(tr)
457 ) {
458 if (load(enStream, trStream, false)) {
459 pluralMode = languages.get(l);
460 loadedCode = l;
461 return true;
462 }
463 } catch (IOException e) {
464 // Ignore exception
465 Logging.trace(e);
466 }
467 return false;
468 }
469
470 private static boolean load(InputStream en, InputStream tr, boolean add) {
471 Map<String, String> s;
472 Map<String, String[]> p;
473 if (add) {
474 s = strings;
475 p = pstrings;
476 } else {
477 s = new HashMap<>();
478 p = new HashMap<>();
479 }
480 /* file format:
481 Files are always a group. English file and translated file must provide identical datasets.
482
483 for all single strings:
484 {
485 unsigned short (2 byte) stringlength
486 - length 0 indicates missing translation
487 - length 0xFFFE indicates translation equal to original, but otherwise is equal to length 0
488 string
489 }
490 unsigned short (2 byte) 0xFFFF (marks end of single strings)
491 for all multi strings:
492 {
493 unsigned char (1 byte) stringcount
494 - count 0 indicates missing translations
495 - count 0xFE indicates translations equal to original, but otherwise is equal to length 0
496 for stringcount
497 unsigned short (2 byte) stringlength
498 string
499 }
500 */
501 try {
502 InputStream ens = new BufferedInputStream(en);
503 InputStream trs = new BufferedInputStream(tr);
504 byte[] enlen = new byte[2];
505 byte[] trlen = new byte[2];
506 boolean multimode = false;
507 byte[] str = new byte[4096];
508 for (;;) {
509 if (multimode) {
510 int ennum = ens.read();
511 int trnum = trs.read();
512 if (trnum == 0xFE) /* marks identical string, handle equally to non-translated */
513 trnum = 0;
514 if ((ennum == -1 && trnum != -1) || (ennum != -1 && trnum == -1)) /* files do not match */
515 return false;
516 if (ennum == -1) {
517 break;
518 }
519 String[] enstrings = new String[ennum];
520 for (int i = 0; i < ennum; ++i) {
521 int val = ens.read(enlen);
522 if (val != 2) /* file corrupt */
523 return false;
524 val = (enlen[0] < 0 ? 256+enlen[0] : enlen[0])*256+(enlen[1] < 0 ? 256+enlen[1] : enlen[1]);
525 if (val > str.length) {
526 str = new byte[val];
527 }
528 int rval = ens.read(str, 0, val);
529 if (rval != val) /* file corrupt */
530 return false;
531 enstrings[i] = new String(str, 0, val, StandardCharsets.UTF_8);
532 }
533 String[] trstrings = new String[trnum];
534 for (int i = 0; i < trnum; ++i) {
535 int val = trs.read(trlen);
536 if (val != 2) /* file corrupt */
537 return false;
538 val = (trlen[0] < 0 ? 256+trlen[0] : trlen[0])*256+(trlen[1] < 0 ? 256+trlen[1] : trlen[1]);
539 if (val > str.length) {
540 str = new byte[val];
541 }
542 int rval = trs.read(str, 0, val);
543 if (rval != val) /* file corrupt */
544 return false;
545 trstrings[i] = new String(str, 0, val, StandardCharsets.UTF_8);
546 }
547 if (trnum > 0 && !p.containsKey(enstrings[0])) {
548 p.put(enstrings[0], trstrings);
549 }
550 } else {
551 int enval = ens.read(enlen);
552 int trval = trs.read(trlen);
553 if (enval != trval) /* files do not match */
554 return false;
555 if (enval == -1) {
556 break;
557 }
558 if (enval != 2) /* files corrupt */
559 return false;
560 enval = (enlen[0] < 0 ? 256+enlen[0] : enlen[0])*256+(enlen[1] < 0 ? 256+enlen[1] : enlen[1]);
561 trval = (trlen[0] < 0 ? 256+trlen[0] : trlen[0])*256+(trlen[1] < 0 ? 256+trlen[1] : trlen[1]);
562 if (trval == 0xFFFE) /* marks identical string, handle equally to non-translated */
563 trval = 0;
564 if (enval == 0xFFFF) {
565 multimode = true;
566 if (trval != 0xFFFF) /* files do not match */
567 return false;
568 } else {
569 if (enval > str.length) {
570 str = new byte[enval];
571 }
572 if (trval > str.length) {
573 str = new byte[trval];
574 }
575 int val = ens.read(str, 0, enval);
576 if (val != enval) /* file corrupt */
577 return false;
578 String enstr = new String(str, 0, enval, StandardCharsets.UTF_8);
579 if (trval != 0) {
580 val = trs.read(str, 0, trval);
581 if (val != trval) /* file corrupt */
582 return false;
583 String trstr = new String(str, 0, trval, StandardCharsets.UTF_8);
584 if (!s.containsKey(enstr))
585 s.put(enstr, trstr);
586 }
587 }
588 }
589 }
590 } catch (IOException e) {
591 Logging.trace(e);
592 return false;
593 }
594 if (!s.isEmpty()) {
595 strings = s;
596 pstrings = p;
597 return true;
598 }
599 return false;
600 }
601
602 /**
603 * Sets the default locale (see {@link Locale#setDefault(Locale)} to the local
604 * given by <code>localName</code>.
605 *
606 * Ignored if localeName is null. If the locale with name <code>localName</code>
607 * isn't found the default local is set to <code>en</code> (english).
608 *
609 * @param localeName the locale name. Ignored if null.
610 */
611 public static void set(String localeName) {
612 if (localeName != null) {
613 Locale l = LanguageInfo.getLocale(localeName, true);
614 if (load(LanguageInfo.getJOSMLocaleCode(l))) {
615 Locale.setDefault(l);
616 } else {
617 if (!"en".equals(l.getLanguage())) {
618 Logging.info(tr("Unable to find translation for the locale {0}. Reverting to {1}.",
619 LanguageInfo.getDisplayName(l), LanguageInfo.getDisplayName(Locale.getDefault())));
620 } else {
621 strings = null;
622 pstrings = null;
623 }
624 }
625 }
626 }
627
628 private static int pluralEval(long n) {
629 switch(pluralMode) {
630 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 */
631 return (n != 1) ? 1 : 0;
632 case MODE_NONE: /* id, vi, ja, km, tr, zh_CN, zh_TW */
633 return 0;
634 case MODE_GREATERONE: /* fr, pt_BR */
635 return (n > 1) ? 1 : 0;
636 case MODE_CS:
637 return (n == 1) ? 0 : (((n >= 2) && (n <= 4)) ? 1 : 2);
638 case MODE_AR:
639 return ((n == 0) ? 0 : ((n == 1) ? 1 : ((n == 2) ? 2 : ((((n % 100) >= 3)
640 && ((n % 100) <= 10)) ? 3 : ((((n % 100) >= 11) && ((n % 100) <= 99)) ? 4 : 5)))));
641 case MODE_PL:
642 return (n == 1) ? 0 : (((((n % 10) >= 2) && ((n % 10) <= 4))
643 && (((n % 100) < 10) || ((n % 100) >= 20))) ? 1 : 2);
644 //case MODE_RO:
645 // return ((n == 1) ? 0 : ((((n % 100) > 19) || (((n % 100) == 0) && (n != 0))) ? 2 : 1));
646 case MODE_LT:
647 return ((n % 10) == 1) && ((n % 100) != 11) ? 0 : (((n % 10) >= 2)
648 && (((n % 100) < 10) || ((n % 100) >= 20)) ? 1 : 2);
649 case MODE_RU:
650 return (((n % 10) == 1) && ((n % 100) != 11)) ? 0 : (((((n % 10) >= 2)
651 && ((n % 10) <= 4)) && (((n % 100) < 10) || ((n % 100) >= 20))) ? 1 : 2);
652 case MODE_SK:
653 return (n == 1) ? 1 : (((n >= 2) && (n <= 4)) ? 2 : 0);
654 //case MODE_SL:
655 // return (((n % 100) == 1) ? 1 : (((n % 100) == 2) ? 2 : ((((n % 100) == 3)
656 // || ((n % 100) == 4)) ? 3 : 0)));
657 }
658 return 0;
659 }
660
661 /**
662 * Returns the map of singular translations.
663 * @return the map of singular translations.
664 * @since 13761
665 */
666 public static Map<String, String> getSingularTranslations() {
667 return new HashMap<>(strings);
668 }
669
670 /**
671 * Returns the map of plural translations.
672 * @return the map of plural translations.
673 * @since 13761
674 */
675 public static Map<String, String[]> getPluralTranslations() {
676 return new HashMap<>(pstrings);
677 }
678
679 /**
680 * Returns the original default locale found when the JVM started.
681 * Used to guess real language/country of current user disregarding language chosen in JOSM preferences.
682 * @return the original default locale found when the JVM started
683 * @since 14013
684 */
685 public static Locale getOriginalLocale() {
686 return originalLocale;
687 }
688
689 /**
690 * Returns the localized name of the given script. Only scripts used in the OSM database are known.
691 * @param script Writing system
692 * @return the localized name of the given script, or null
693 * @since 15501
694 */
695 public static String getLocalizedScript(String script) {
696 if (script != null) {
697 switch (script.toLowerCase(Locale.ENGLISH)) {
698 case HIRAGANA:
699 return /* I18n: a Japanese syllabary */ tr("Hiragana");
700 case KATAKANA:
701 return /* I18n: a Japanese syllabary */ tr("Katakana");
702 case LATIN:
703 return /* I18n: usage of latin letters/script for usually non-latin languages */ tr("Latin");
704 case PINYIN:
705 return /* I18n: official romanization system for Standard Chinese */ tr("Pinyin");
706 case ROMAJI:
707 return /* I18n: a Japanese syllabary (latin script) */ tr("Rōmaji");
708 default:
709 Logging.warn("Unsupported script: {0}", script);
710 }
711 }
712 return null;
713 }
714
715 /**
716 * Returns the localized name of the given language and optional script.
717 * @param language Language
718 * @return the pair of localized name + known state of the given language, or null
719 * @since 15501
720 */
721 public static Pair<String, Boolean> getLocalizedLanguageName(String language) {
722 Matcher m = LANGUAGE_NAMES.matcher(language);
723 if (m.matches()) {
724 String code = m.group(1);
725 String label = new Locale(code).getDisplayLanguage();
726 boolean knownNameKey = !code.equals(label);
727 String script = getLocalizedScript(m.group(2));
728 if (script != null) {
729 label += " (" + script + ")";
730 }
731 return new Pair<>(label, knownNameKey);
732 }
733 return null;
734 }
735}
Note: See TracBrowser for help on using the repository browser.