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

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

fix Hebrew language handling, i18n update

  • Property svn:eol-style set to native
File size: 23.6 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 void init()
304 {
305 languages.put("ar", PluralMode.MODE_AR);
306 languages.put("bg", PluralMode.MODE_NOTONE);
307 languages.put("cs", PluralMode.MODE_CS);
308 languages.put("da", PluralMode.MODE_NOTONE);
309 languages.put("de", PluralMode.MODE_NOTONE);
310 languages.put("el", PluralMode.MODE_NOTONE);
311 languages.put("en_AU", PluralMode.MODE_NOTONE);
312 languages.put("en_GB", PluralMode.MODE_NOTONE);
313 languages.put("es", PluralMode.MODE_NOTONE);
314 languages.put("et", PluralMode.MODE_NOTONE);
315 languages.put("eu", PluralMode.MODE_NOTONE);
316 languages.put("fi", PluralMode.MODE_NOTONE);
317 languages.put("fr", PluralMode.MODE_GREATERONE);
318 languages.put("gl", PluralMode.MODE_NOTONE);
319 languages.put("he", PluralMode.MODE_NOTONE);
320 //languages.put("id", PluralMode.MODE_NONE);
321 languages.put("is", PluralMode.MODE_NOTONE);
322 languages.put("it", PluralMode.MODE_NOTONE);
323 languages.put("ja", PluralMode.MODE_NONE);
324 languages.put("nb", PluralMode.MODE_NOTONE);
325 languages.put("nl", PluralMode.MODE_NOTONE);
326 languages.put("pl", PluralMode.MODE_PL);
327 languages.put("pt_BR", PluralMode.MODE_GREATERONE);
328 //languages.put("ro", PluralMode.MODE_RO);
329 languages.put("ru", PluralMode.MODE_RU);
330 languages.put("sk", PluralMode.MODE_SK);
331 //languages.put("sl", PluralMode.MODE_SL);
332 languages.put("sv", PluralMode.MODE_NOTONE);
333 languages.put("tr", PluralMode.MODE_NONE);
334 languages.put("uk", PluralMode.MODE_RU);
335 languages.put("zh_CN", PluralMode.MODE_NONE);
336 languages.put("zh_TW", PluralMode.MODE_NONE);
337
338 /* try initial language settings, may be changed later again */
339 if(!load(Locale.getDefault().toString())) {
340 Locale.setDefault(Locale.ENGLISH);
341 }
342 }
343
344 public static void addTexts(File source)
345 {
346 if(loadedCode.equals("en"))
347 return;
348 FileInputStream fis = null;
349 JarInputStream jar = null;
350 FileInputStream fisTrans = null;
351 JarInputStream jarTrans = null;
352 String enfile = "data/en.lang";
353 String langfile = "data/"+loadedCode+".lang";
354 try
355 {
356 ZipEntry e;
357 fis = new FileInputStream(source);
358 jar = new JarInputStream(fis);
359 boolean found = false;
360 while(!found && (e = jar.getNextEntry()) != null)
361 {
362 String name = e.getName();
363 if(name.equals(enfile))
364 found = true;
365 }
366 if(found)
367 {
368 fisTrans = new FileInputStream(source);
369 jarTrans = new JarInputStream(fisTrans);
370 found = false;
371 while(!found && (e = jarTrans.getNextEntry()) != null)
372 {
373 String name = e.getName();
374 if(name.equals(langfile))
375 found = true;
376 }
377 if(found)
378 load(jar, jarTrans, true);
379 }
380 }
381 catch(IOException e)
382 {
383 }
384 finally
385 {
386 try
387 {
388 if(jar != null)
389 jar.close();
390 if(fis != null)
391 fis.close();
392 if(jarTrans != null)
393 jarTrans.close();
394 if(fisTrans != null)
395 fisTrans.close();
396 }
397 catch(IOException e)
398 {
399 }
400 }
401 }
402
403 private static boolean load(String l)
404 {
405 if(l.equals("en") || l.equals("en_US"))
406 {
407 strings = null;
408 pstrings = null;
409 loadedCode = "en";
410 pluralMode = PluralMode.MODE_NOTONE;
411 return true;
412 }
413 URL en = Main.class.getResource("/data/en.lang");
414 if(en == null)
415 return false;
416 URL tr = Main.class.getResource("/data/"+l+".lang");
417 if(tr == null || !languages.containsKey(l))
418 {
419 int i = l.indexOf('_');
420 if (i > 0) {
421 l = l.substring(0, i);
422 }
423 tr = Main.class.getResource("/data/"+l+".lang");
424 if(tr == null || !languages.containsKey(l))
425 return false;
426 }
427 try
428 {
429 if(load(en.openStream(), tr.openStream(), false))
430 {
431 pluralMode = languages.get(l);
432 loadedCode = l;
433 return true;
434 }
435 }
436 catch(IOException e)
437 {
438 }
439 return false;
440 }
441
442 private static boolean load(InputStream en, InputStream tr, boolean add)
443 {
444 HashMap<String, String> s;
445 HashMap<String, String[]> p;
446 if(add)
447 {
448 s = strings;
449 p = pstrings;
450 }
451 else
452 {
453 s = new HashMap<String, String>();
454 p = new HashMap<String, String[]>();
455 }
456 /* file format:
457 for all single strings:
458 {
459 unsigned short (2 byte) stringlength
460 string
461 }
462 unsigned short (2 byte) 0xFFFF (marks end of single strings)
463 for all multi strings:
464 {
465 unsigned char (1 byte) stringcount
466 for stringcount
467 unsigned short (2 byte) stringlength
468 string
469 }
470 */
471 try
472 {
473 InputStream ens = new BufferedInputStream(en);
474 InputStream trs = new BufferedInputStream(tr);
475 byte[] enlen = new byte[2];
476 byte[] trlen = new byte[2];
477 boolean multimode = false;
478 byte[] str = new byte[4096];
479 for(;;)
480 {
481 if(multimode)
482 {
483 int ennum = ens.read();
484 int trnum = trs.read();
485 if((ennum == -1 && trnum != -1) || (ennum != -1 && trnum == -1)) /* files do not match */
486 return false;
487 if(ennum == -1) {
488 break;
489 }
490 String[] enstrings = new String[ennum];
491 String[] trstrings = new String[trnum];
492 for(int i = 0; i < ennum; ++i)
493 {
494 int val = ens.read(enlen);
495 if(val != 2) /* file corrupt */
496 return false;
497 val = (enlen[0] < 0 ? 256+enlen[0]:enlen[0])*256+(enlen[1] < 0 ? 256+enlen[1]:enlen[1]);
498 if(val > str.length) {
499 str = new byte[val];
500 }
501 int rval = ens.read(str, 0, val);
502 if(rval != val) /* file corrupt */
503 return false;
504 enstrings[i] = new String(str, 0, val, "utf-8");
505 }
506 for(int i = 0; i < trnum; ++i)
507 {
508 int val = trs.read(trlen);
509 if(val != 2) /* file corrupt */
510 return false;
511 val = (trlen[0] < 0 ? 256+trlen[0]:trlen[0])*256+(trlen[1] < 0 ? 256+trlen[1]:trlen[1]);
512 if(val > str.length) {
513 str = new byte[val];
514 }
515 int rval = trs.read(str, 0, val);
516 if(rval != val) /* file corrupt */
517 return false;
518 trstrings[i] = new String(str, 0, val, "utf-8");
519 }
520 if(trnum > 0 && !p.containsKey(enstrings[0])) {
521 p.put(enstrings[0], trstrings);
522 }
523 }
524 else
525 {
526 int enval = ens.read(enlen);
527 int trval = trs.read(trlen);
528 if(enval != trval) /* files do not match */
529 return false;
530 if(enval == -1) {
531 break;
532 }
533 if(enval != 2) /* files corrupt */
534 return false;
535 enval = (enlen[0] < 0 ? 256+enlen[0]:enlen[0])*256+(enlen[1] < 0 ? 256+enlen[1]:enlen[1]);
536 trval = (trlen[0] < 0 ? 256+trlen[0]:trlen[0])*256+(trlen[1] < 0 ? 256+trlen[1]:trlen[1]);
537 if(enval == 0xFFFF)
538 {
539 multimode = true;
540 if(trval != 0xFFFF) /* files do not match */
541 return false;
542 }
543 else
544 {
545 if(enval > str.length) {
546 str = new byte[enval];
547 }
548 if(trval > str.length) {
549 str = new byte[trval];
550 }
551 int val = ens.read(str, 0, enval);
552 if(val != enval) /* file corrupt */
553 return false;
554 String enstr = new String(str, 0, enval, "utf-8");
555 if(trval != 0)
556 {
557 val = trs.read(str, 0, trval);
558 if(val != trval) /* file corrupt */
559 return false;
560 String trstr = new String(str, 0, trval, "utf-8");
561 if(!s.containsKey(enstr))
562 s.put(enstr, trstr);
563 }
564 }
565 }
566 }
567 }
568 catch(IOException e)
569 {
570 return false;
571 }
572 if(!s.isEmpty())
573 {
574 strings = s;
575 pstrings = p;
576 return true;
577 }
578 return false;
579 }
580
581 /**
582 * Sets the default locale (see {@see Locale#setDefault(Locale)} to the local
583 * given by <code>localName</code>.
584 *
585 * Ignored if localeName is null. If the locale with name <code>localName</code>
586 * isn't found the default local is set to <tt>en</tt> (english).
587 *
588 * @param localeName the locale name. Ignored if null.
589 */
590 public static void set(String localeName){
591 if (localeName != null) {
592 Locale l = LanguageInfo.getLocale(localeName);
593 if (load(LanguageInfo.getJOSMLocaleCode(l))) {
594 Locale.setDefault(l);
595 } else {
596 if (!l.getLanguage().equals("en")) {
597 System.out.println(tr("Unable to find translation for the locale {0}. Reverting to {1}.",
598 l.getDisplayName(), Locale.getDefault().getDisplayName()));
599 } else {
600 strings = null;
601 pstrings = null;
602 }
603 }
604 }
605 }
606
607 /**
608 * Localizations for file chooser dialog.
609 * For some locales (e.g. de, fr) translations are provided
610 * by Java, but not for others (e.g. ru, uk).
611 */
612 public static void translateJavaInternalMessages() {
613 Locale l = Locale.getDefault();
614
615 JFileChooser.setDefaultLocale(l);
616 JColorChooser.setDefaultLocale(l);
617 for (String key : javaInternalMessageKeys) {
618 String us = UIManager.getString(key, Locale.US);
619 String loc = UIManager.getString(key, l);
620 // only provide custom translation if it is not already localized by Java
621 if (us != null && us.equals(loc)) {
622 UIManager.put(key, tr(us));
623 }
624 }
625 }
626
627 private static int pluralEval(long n)
628 {
629 switch(pluralMode)
630 {
631 case MODE_NOTONE: /* bg, da, de, el, en, en_GB, es, et, eu, fi, gl, is, it, iw_IL, nb, nl, sv */
632 return ((n != 1) ? 1 : 0);
633 case MODE_NONE: /* ja, tr, zh_CN, zh_TW */
634 return 0;
635 case MODE_GREATERONE: /* fr, pt_BR */
636 return ((n > 1) ? 1 : 0);
637 case MODE_CS:
638 return ((n == 1) ? 0 : (((n >= 2) && (n <= 4)) ? 1 : 2));
639 case MODE_AR:
640 return ((n == 0) ? 0 : ((n == 1) ? 1 : ((n == 2) ? 2 : ((((n % 100) >= 3)
641 && ((n % 100) <= 10)) ? 3 : ((((n % 100) >= 11) && ((n % 100) <= 99)) ? 4 : 5)))));
642 case MODE_PL:
643 return ((n == 1) ? 0 : (((((n % 10) >= 2) && ((n % 10) <= 4))
644 && (((n % 100) < 10) || ((n % 100) >= 20))) ? 1 : 2));
645 //case MODE_RO:
646 // return ((n == 1) ? 0 : ((((n % 100) > 19) || (((n % 100) == 0) && (n != 0))) ? 2 : 1));
647 case MODE_RU:
648 return ((((n % 10) == 1) && ((n % 100) != 11)) ? 0 : (((((n % 10) >= 2)
649 && ((n % 10) <= 4)) && (((n % 100) < 10) || ((n % 100) >= 20))) ? 1 : 2));
650 case MODE_SK:
651 return ((n == 1) ? 1 : (((n >= 2) && (n <= 4)) ? 2 : 0));
652 //case MODE_SL:
653 // return (((n % 100) == 1) ? 1 : (((n % 100) == 2) ? 2 : ((((n % 100) == 3)
654 // || ((n % 100) == 4)) ? 3 : 0)));
655 }
656 return 0;
657 }
658}
Note: See TracBrowser for help on using the repository browser.