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