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

Last change on this file since 4212 was 4212, checked in by stoecker, 13 years ago

reduce hardcoded I18n parts

  • Property svn:eol-style set to native
File size: 23.7 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.tools;
3
4import java.io.BufferedInputStream;
5import java.io.File;
6import java.io.FileInputStream;
7import java.io.InputStream;
8import java.io.IOException;
9import java.net.URL;
10import java.text.MessageFormat;
11import java.util.Arrays;
12import java.util.Comparator;
13import java.util.HashMap;
14import java.util.jar.JarInputStream;
15import java.util.zip.ZipEntry;
16import java.util.Locale;
17import java.util.Vector;
18
19import javax.swing.JColorChooser;
20import javax.swing.JFileChooser;
21import javax.swing.UIManager;
22
23import org.openstreetmap.josm.Main;
24
25/**
26 * Internationalisation support.
27 *
28 * @author Immanuel.Scholz
29 */
30public class I18n {
31 private enum PluralMode { MODE_NOTONE, MODE_NONE, MODE_GREATERONE,
32 MODE_CS, MODE_AR, MODE_PL/*, MODE_RO*/, MODE_RU, MODE_SK/*, MODE_SL*/}
33 private static PluralMode pluralMode = PluralMode.MODE_NOTONE; /* english default */
34 private static String loadedCode = "en";
35
36 /* Localization keys for file chooser (and color chooser). */
37 private static final String[] javaInternalMessageKeys = new String[] {
38 /* JFileChooser windows laf */
39 "FileChooser.detailsViewActionLabelText",
40 "FileChooser.detailsViewButtonAccessibleName",
41 "FileChooser.detailsViewButtonToolTipText",
42 "FileChooser.fileAttrHeaderText",
43 "FileChooser.fileDateHeaderText",
44 "FileChooser.fileNameHeaderText",
45 "FileChooser.fileNameLabelText",
46 "FileChooser.fileSizeHeaderText",
47 "FileChooser.fileTypeHeaderText",
48 "FileChooser.filesOfTypeLabelText",
49 "FileChooser.homeFolderAccessibleName",
50 "FileChooser.homeFolderToolTipText",
51 "FileChooser.listViewActionLabelText",
52 "FileChooser.listViewButtonAccessibleName",
53 "FileChooser.listViewButtonToolTipText",
54 "FileChooser.lookInLabelText",
55 "FileChooser.newFolderAccessibleName",
56 "FileChooser.newFolderActionLabelText",
57 "FileChooser.newFolderToolTipText",
58 "FileChooser.refreshActionLabelText",
59 "FileChooser.saveInLabelText",
60 "FileChooser.upFolderAccessibleName",
61 "FileChooser.upFolderToolTipText",
62 "FileChooser.viewMenuLabelText",
63
64 /* JFileChooser gtk laf */
65 "FileChooser.acceptAllFileFilterText",
66 "FileChooser.cancelButtonText",
67 "FileChooser.cancelButtonToolTipText",
68 "FileChooser.deleteFileButtonText",
69 "FileChooser.filesLabelText",
70 "FileChooser.filterLabelText",
71 "FileChooser.foldersLabelText",
72 "FileChooser.newFolderButtonText",
73 "FileChooser.newFolderDialogText",
74 "FileChooser.openButtonText",
75 "FileChooser.openButtonToolTipText",
76 "FileChooser.openDialogTitleText",
77 "FileChooser.pathLabelText",
78 "FileChooser.renameFileButtonText",
79 "FileChooser.renameFileDialogText",
80 "FileChooser.renameFileErrorText",
81 "FileChooser.renameFileErrorTitle",
82 "FileChooser.saveButtonText",
83 "FileChooser.saveButtonToolTipText",
84 "FileChooser.saveDialogTitleText",
85
86 /* JFileChooser motif laf */
87 //"FileChooser.cancelButtonText",
88 //"FileChooser.cancelButtonToolTipText",
89 "FileChooser.enterFileNameLabelText",
90 //"FileChooser.filesLabelText",
91 //"FileChooser.filterLabelText",
92 //"FileChooser.foldersLabelText",
93 "FileChooser.helpButtonText",
94 "FileChooser.helpButtonToolTipText",
95 //"FileChooser.openButtonText",
96 //"FileChooser.openButtonToolTipText",
97 //"FileChooser.openDialogTitleText",
98 //"FileChooser.pathLabelText",
99 //"FileChooser.saveButtonText",
100 //"FileChooser.saveButtonToolTipText",
101 //"FileChooser.saveDialogTitleText",
102 "FileChooser.updateButtonText",
103 "FileChooser.updateButtonToolTipText",
104
105 /* gtk color chooser */
106 "GTKColorChooserPanel.blueText",
107 "GTKColorChooserPanel.colorNameText",
108 "GTKColorChooserPanel.greenText",
109 "GTKColorChooserPanel.hueText",
110 "GTKColorChooserPanel.nameText",
111 "GTKColorChooserPanel.redText",
112 "GTKColorChooserPanel.saturationText",
113 "GTKColorChooserPanel.valueText",
114
115 /* JOptionPane */
116 "OptionPane.okButtonText",
117 "OptionPane.yesButtonText",
118 "OptionPane.noButtonText",
119 "OptionPane.cancelButtonText"
120 };
121 private static HashMap<String, String> strings = null;
122 private static HashMap<String, String[]> pstrings = null;
123 private static HashMap<String, PluralMode> languages = new HashMap<String, PluralMode>();
124
125 /**
126 * Translates some text for the current locale.
127 * These strings are collected by a script that runs on the source code files.
128 * After translation, the localizations are distributed with the main program.
129 *
130 * @param text the text to translate.
131 * Must be a string literal. (No constants or local vars.)
132 * Can be broken over multiple lines.
133 * An apostrophe ' must be quoted by another apostrophe.
134 * @param objects Parameters for the string.
135 * Mark occurrences in <code>text</code> with {0}, {1}, ...
136 * @return the translated string
137 *
138 * Example: tr("JOSM''s default value is ''{0}''.", val);
139 */
140 public static final String tr(String text, Object... objects) {
141 return MessageFormat.format(gettext(text, null), objects);
142 }
143
144 public static final String tr(String text) {
145 if (text == null)
146 return null;
147 return MessageFormat.format(gettext(text, null), (Object)null);
148 }
149
150 /**
151 * Provide translation in a context.
152 * There can be different translations for the same text (but
153 * different context).
154 *
155 * @param context string that helps translators to find an appropriate
156 * translation for <code>text</code>
157 * @param text the text to translate
158 * @return the translated string
159 */
160 public static final String trc(String context, String text) {
161 if (context == null)
162 return tr(text);
163 if (text == null)
164 return null;
165 return MessageFormat.format(gettext(text, context), (Object)null);
166 }
167
168 public static final String trc_lazy(String context, String text) {
169 if (context == null)
170 return tr(text);
171 if (text == null)
172 return null;
173 return MessageFormat.format(gettext_lazy(text, context), (Object)null);
174 }
175
176 /**
177 * Marks a string for translation (such that a script can harvest
178 * the translatable strings from the source files).
179 *
180 * Example:
181 * String[] options = new String[] {marktr("up"), marktr("down")};
182 * lbl.setText(tr(options[0]));
183 */
184 public static final String marktr(String text) {
185 return text;
186 }
187
188 public static final String marktrc(String context, String text) {
189 return text;
190 }
191
192 /**
193 * Example: trn("Found {0} error in {1}!", "Found {0} errors in {1}!", i, Integer.toString(i), url);
194 */
195 public static final String trn(String text, String pluralText, long n, Object... objects) {
196 return MessageFormat.format(gettextn(text, pluralText, null, n), objects);
197 }
198
199 /**
200 * Example: trn("There was an error!", "There were errors!", i);
201 */
202 public static final String trn(String text, String pluralText, long n) {
203 return MessageFormat.format(gettextn(text, pluralText, null, n), (Object)null);
204 }
205
206 public static final String trnc(String ctx, String text, String pluralText, long n, Object... objects) {
207 return MessageFormat.format(gettextn(text, pluralText, ctx, n), objects);
208 }
209
210 public static final String trnc(String ctx, String text, String pluralText, long n) {
211 return MessageFormat.format(gettextn(text, pluralText, ctx, n), (Object)null);
212 }
213
214 private static final String gettext(String text, String ctx)
215 {
216 int i;
217 if(ctx == null && text.startsWith("_:") && (i = text.indexOf("\n")) >= 0)
218 {
219 ctx = text.substring(2,i-1);
220 text = text.substring(i+1);
221 }
222 if(strings != null)
223 {
224 String trans = strings.get(ctx == null ? text : "_:"+ctx+"\n"+text);
225 if(trans != null)
226 return trans;
227 }
228 if(pstrings != null) {
229 String[] trans = pstrings.get(ctx == null ? text : "_:"+ctx+"\n"+text);
230 if(trans != null)
231 return trans[0];
232 }
233 return text;
234 }
235
236 /* try without context, when context try fails */
237 private static final String gettext_lazy(String text, String ctx)
238 {
239 int i;
240 if(ctx == null && text.startsWith("_:") && (i = text.indexOf("\n")) >= 0)
241 {
242 ctx = text.substring(2,i-1);
243 text = text.substring(i+1);
244 }
245 if(strings != null)
246 {
247 String trans = strings.get(ctx == null ? text : "_:"+ctx+"\n"+text);
248 if(trans != null)
249 return trans;
250 }
251 if(pstrings != null) {
252 String[] trans = pstrings.get(ctx == null ? text : "_:"+ctx+"\n"+text);
253 if(trans != null)
254 return trans[0];
255 }
256 return gettext(text, null);
257 }
258
259 private static final String gettextn(String text, String plural, String ctx, long num)
260 {
261 int i;
262 if(ctx == null && text.startsWith("_:") && (i = text.indexOf("\n")) >= 0)
263 {
264 ctx = text.substring(2,i-1);
265 text = text.substring(i+1);
266 }
267 if(pstrings != null)
268 {
269 i = pluralEval(num);
270 String[] trans = pstrings.get(ctx == null ? text : "_:"+ctx+"\n"+text);
271 if(trans != null && trans.length > i)
272 return trans[i];
273 }
274
275 return num == 1 ? text : plural;
276 }
277
278 /**
279 * Get a list of all available JOSM Translations.
280 * @return an array of locale objects.
281 */
282 public static final Locale[] getAvailableTranslations() {
283 Vector<Locale> v = new Vector<Locale>();
284 if(Main.class.getResource("/data/en.lang") != null)
285 {
286 for (String loc : languages.keySet()) {
287 if(Main.class.getResource("/data/"+loc+".lang") != null) {
288 v.add(LanguageInfo.getLocale(loc));
289 }
290 }
291 }
292 v.add(Locale.ENGLISH);
293 Locale[] l = new Locale[v.size()];
294 l = v.toArray(l);
295 Arrays.sort(l, new Comparator<Locale>() {
296 public int compare(Locale o1, Locale o2) {
297 return o1.toString().compareTo(o2.toString());
298 }
299 });
300 return l;
301 }
302
303 public static boolean hasCode(String code)
304 {
305 return languages.containsKey(code);
306 }
307
308 public static void init()
309 {
310 languages.put("ar", PluralMode.MODE_AR);
311 languages.put("bg", PluralMode.MODE_NOTONE);
312 languages.put("cs", PluralMode.MODE_CS);
313 languages.put("da", PluralMode.MODE_NOTONE);
314 languages.put("de", PluralMode.MODE_NOTONE);
315 languages.put("el", PluralMode.MODE_NOTONE);
316 languages.put("en_AU", PluralMode.MODE_NOTONE);
317 languages.put("en_GB", PluralMode.MODE_NOTONE);
318 languages.put("es", PluralMode.MODE_NOTONE);
319 languages.put("et", PluralMode.MODE_NOTONE);
320 languages.put("eu", PluralMode.MODE_NOTONE);
321 languages.put("fi", PluralMode.MODE_NOTONE);
322 languages.put("fr", PluralMode.MODE_GREATERONE);
323 languages.put("gl", PluralMode.MODE_NOTONE);
324 languages.put("he", PluralMode.MODE_NOTONE);
325 //languages.put("id", PluralMode.MODE_NONE);
326 languages.put("is", PluralMode.MODE_NOTONE);
327 languages.put("it", PluralMode.MODE_NOTONE);
328 languages.put("ja", PluralMode.MODE_NONE);
329 languages.put("nb", PluralMode.MODE_NOTONE);
330 languages.put("nl", PluralMode.MODE_NOTONE);
331 languages.put("pl", PluralMode.MODE_PL);
332 languages.put("pt_BR", PluralMode.MODE_GREATERONE);
333 //languages.put("ro", PluralMode.MODE_RO);
334 languages.put("ru", PluralMode.MODE_RU);
335 languages.put("sk", PluralMode.MODE_SK);
336 //languages.put("sl", PluralMode.MODE_SL);
337 languages.put("sv", PluralMode.MODE_NOTONE);
338 languages.put("tr", PluralMode.MODE_NONE);
339 languages.put("uk", PluralMode.MODE_RU);
340 languages.put("zh_CN", PluralMode.MODE_NONE);
341 languages.put("zh_TW", PluralMode.MODE_NONE);
342
343 /* try initial language settings, may be changed later again */
344 if(!load(Locale.getDefault().toString())) {
345 Locale.setDefault(Locale.ENGLISH);
346 }
347 }
348
349 public static void addTexts(File source)
350 {
351 if(loadedCode.equals("en"))
352 return;
353 FileInputStream fis = null;
354 JarInputStream jar = null;
355 FileInputStream fisTrans = null;
356 JarInputStream jarTrans = null;
357 String enfile = "data/en.lang";
358 String langfile = "data/"+loadedCode+".lang";
359 try
360 {
361 ZipEntry e;
362 fis = new FileInputStream(source);
363 jar = new JarInputStream(fis);
364 boolean found = false;
365 while(!found && (e = jar.getNextEntry()) != null)
366 {
367 String name = e.getName();
368 if(name.equals(enfile))
369 found = true;
370 }
371 if(found)
372 {
373 fisTrans = new FileInputStream(source);
374 jarTrans = new JarInputStream(fisTrans);
375 found = false;
376 while(!found && (e = jarTrans.getNextEntry()) != null)
377 {
378 String name = e.getName();
379 if(name.equals(langfile))
380 found = true;
381 }
382 if(found)
383 load(jar, jarTrans, true);
384 }
385 }
386 catch(IOException e)
387 {
388 }
389 finally
390 {
391 try
392 {
393 if(jar != null)
394 jar.close();
395 if(fis != null)
396 fis.close();
397 if(jarTrans != null)
398 jarTrans.close();
399 if(fisTrans != null)
400 fisTrans.close();
401 }
402 catch(IOException e)
403 {
404 }
405 }
406 }
407
408 private static boolean load(String l)
409 {
410 if(l.equals("en") || l.equals("en_US"))
411 {
412 strings = null;
413 pstrings = null;
414 loadedCode = "en";
415 pluralMode = PluralMode.MODE_NOTONE;
416 return true;
417 }
418 URL en = Main.class.getResource("/data/en.lang");
419 if(en == null)
420 return false;
421 URL tr = Main.class.getResource("/data/"+l+".lang");
422 if(tr == null || !languages.containsKey(l))
423 {
424 int i = l.indexOf('_');
425 if (i > 0) {
426 l = l.substring(0, i);
427 }
428 tr = Main.class.getResource("/data/"+l+".lang");
429 if(tr == null || !languages.containsKey(l))
430 return false;
431 }
432 try
433 {
434 if(load(en.openStream(), tr.openStream(), false))
435 {
436 pluralMode = languages.get(l);
437 loadedCode = l;
438 return true;
439 }
440 }
441 catch(IOException e)
442 {
443 }
444 return false;
445 }
446
447 private static boolean load(InputStream en, InputStream tr, boolean add)
448 {
449 HashMap<String, String> s;
450 HashMap<String, String[]> p;
451 if(add)
452 {
453 s = strings;
454 p = pstrings;
455 }
456 else
457 {
458 s = new HashMap<String, String>();
459 p = new HashMap<String, String[]>();
460 }
461 /* file format:
462 for all single strings:
463 {
464 unsigned short (2 byte) stringlength
465 string
466 }
467 unsigned short (2 byte) 0xFFFF (marks end of single strings)
468 for all multi strings:
469 {
470 unsigned char (1 byte) stringcount
471 for stringcount
472 unsigned short (2 byte) stringlength
473 string
474 }
475 */
476 try
477 {
478 InputStream ens = new BufferedInputStream(en);
479 InputStream trs = new BufferedInputStream(tr);
480 byte[] enlen = new byte[2];
481 byte[] trlen = new byte[2];
482 boolean multimode = false;
483 byte[] str = new byte[4096];
484 for(;;)
485 {
486 if(multimode)
487 {
488 int ennum = ens.read();
489 int trnum = trs.read();
490 if((ennum == -1 && trnum != -1) || (ennum != -1 && trnum == -1)) /* files do not match */
491 return false;
492 if(ennum == -1) {
493 break;
494 }
495 String[] enstrings = new String[ennum];
496 String[] trstrings = new String[trnum];
497 for(int i = 0; i < ennum; ++i)
498 {
499 int val = ens.read(enlen);
500 if(val != 2) /* file corrupt */
501 return false;
502 val = (enlen[0] < 0 ? 256+enlen[0]:enlen[0])*256+(enlen[1] < 0 ? 256+enlen[1]:enlen[1]);
503 if(val > str.length) {
504 str = new byte[val];
505 }
506 int rval = ens.read(str, 0, val);
507 if(rval != val) /* file corrupt */
508 return false;
509 enstrings[i] = new String(str, 0, val, "utf-8");
510 }
511 for(int i = 0; i < trnum; ++i)
512 {
513 int val = trs.read(trlen);
514 if(val != 2) /* file corrupt */
515 return false;
516 val = (trlen[0] < 0 ? 256+trlen[0]:trlen[0])*256+(trlen[1] < 0 ? 256+trlen[1]:trlen[1]);
517 if(val > str.length) {
518 str = new byte[val];
519 }
520 int rval = trs.read(str, 0, val);
521 if(rval != val) /* file corrupt */
522 return false;
523 trstrings[i] = new String(str, 0, val, "utf-8");
524 }
525 if(trnum > 0 && !p.containsKey(enstrings[0])) {
526 p.put(enstrings[0], trstrings);
527 }
528 }
529 else
530 {
531 int enval = ens.read(enlen);
532 int trval = trs.read(trlen);
533 if(enval != trval) /* files do not match */
534 return false;
535 if(enval == -1) {
536 break;
537 }
538 if(enval != 2) /* files corrupt */
539 return false;
540 enval = (enlen[0] < 0 ? 256+enlen[0]:enlen[0])*256+(enlen[1] < 0 ? 256+enlen[1]:enlen[1]);
541 trval = (trlen[0] < 0 ? 256+trlen[0]:trlen[0])*256+(trlen[1] < 0 ? 256+trlen[1]:trlen[1]);
542 if(enval == 0xFFFF)
543 {
544 multimode = true;
545 if(trval != 0xFFFF) /* files do not match */
546 return false;
547 }
548 else
549 {
550 if(enval > str.length) {
551 str = new byte[enval];
552 }
553 if(trval > str.length) {
554 str = new byte[trval];
555 }
556 int val = ens.read(str, 0, enval);
557 if(val != enval) /* file corrupt */
558 return false;
559 String enstr = new String(str, 0, enval, "utf-8");
560 if(trval != 0)
561 {
562 val = trs.read(str, 0, trval);
563 if(val != trval) /* file corrupt */
564 return false;
565 String trstr = new String(str, 0, trval, "utf-8");
566 if(!s.containsKey(enstr))
567 s.put(enstr, trstr);
568 }
569 }
570 }
571 }
572 }
573 catch(IOException e)
574 {
575 return false;
576 }
577 if(!s.isEmpty())
578 {
579 strings = s;
580 pstrings = p;
581 return true;
582 }
583 return false;
584 }
585
586 /**
587 * Sets the default locale (see {@see Locale#setDefault(Locale)} to the local
588 * given by <code>localName</code>.
589 *
590 * Ignored if localeName is null. If the locale with name <code>localName</code>
591 * isn't found the default local is set to <tt>en</tt> (english).
592 *
593 * @param localeName the locale name. Ignored if null.
594 */
595 public static void set(String localeName){
596 if (localeName != null) {
597 Locale l = LanguageInfo.getLocale(localeName);
598 if (load(LanguageInfo.getJOSMLocaleCode(l))) {
599 Locale.setDefault(l);
600 } else {
601 if (!l.getLanguage().equals("en")) {
602 System.out.println(tr("Unable to find translation for the locale {0}. Reverting to {1}.",
603 l.getDisplayName(), Locale.getDefault().getDisplayName()));
604 } else {
605 strings = null;
606 pstrings = null;
607 }
608 }
609 }
610 }
611
612 /**
613 * Localizations for file chooser dialog.
614 * For some locales (e.g. de, fr) translations are provided
615 * by Java, but not for others (e.g. ru, uk).
616 */
617 public static void translateJavaInternalMessages() {
618 Locale l = Locale.getDefault();
619
620 JFileChooser.setDefaultLocale(l);
621 JColorChooser.setDefaultLocale(l);
622 for (String key : javaInternalMessageKeys) {
623 String us = UIManager.getString(key, Locale.US);
624 String loc = UIManager.getString(key, l);
625 // only provide custom translation if it is not already localized by Java
626 if (us != null && us.equals(loc)) {
627 UIManager.put(key, tr(us));
628 }
629 }
630 }
631
632 private static int pluralEval(long n)
633 {
634 switch(pluralMode)
635 {
636 case MODE_NOTONE: /* bg, da, de, el, en, en_GB, es, et, eu, fi, gl, is, it, iw_IL, nb, nl, sv */
637 return ((n != 1) ? 1 : 0);
638 case MODE_NONE: /* ja, tr, zh_CN, zh_TW */
639 return 0;
640 case MODE_GREATERONE: /* fr, pt_BR */
641 return ((n > 1) ? 1 : 0);
642 case MODE_CS:
643 return ((n == 1) ? 0 : (((n >= 2) && (n <= 4)) ? 1 : 2));
644 case MODE_AR:
645 return ((n == 0) ? 0 : ((n == 1) ? 1 : ((n == 2) ? 2 : ((((n % 100) >= 3)
646 && ((n % 100) <= 10)) ? 3 : ((((n % 100) >= 11) && ((n % 100) <= 99)) ? 4 : 5)))));
647 case MODE_PL:
648 return ((n == 1) ? 0 : (((((n % 10) >= 2) && ((n % 10) <= 4))
649 && (((n % 100) < 10) || ((n % 100) >= 20))) ? 1 : 2));
650 //case MODE_RO:
651 // return ((n == 1) ? 0 : ((((n % 100) > 19) || (((n % 100) == 0) && (n != 0))) ? 2 : 1));
652 case MODE_RU:
653 return ((((n % 10) == 1) && ((n % 100) != 11)) ? 0 : (((((n % 10) >= 2)
654 && ((n % 10) <= 4)) && (((n % 100) < 10) || ((n % 100) >= 20))) ? 1 : 2));
655 case MODE_SK:
656 return ((n == 1) ? 1 : (((n >= 2) && (n <= 4)) ? 2 : 0));
657 //case MODE_SL:
658 // return (((n % 100) == 1) ? 1 : (((n % 100) == 2) ? 2 : ((((n % 100) == 3)
659 // || ((n % 100) == 4)) ? 3 : 0)));
660 }
661 return 0;
662 }
663}
Note: See TracBrowser for help on using the repository browser.