source: src/mlx/i18n.py@ 296:6833d73f7a44

Last change on this file since 296:6833d73f7a44 was 276:b7b25febba1a, checked in by István Váradi <ivaradi@…>, 12 years ago

Using gettext to translate strings

File size: 2.5 KB
Line 
1# Internationalization support
2# -*- coding: utf-8 -*-
3
4#------------------------------------------------------------------------------
5
6import gettext
7import os
8import traceback
9
10#------------------------------------------------------------------------------
11
12_translation = None
13_language = None
14
15#------------------------------------------------------------------------------
16
17def setLanguage(programDirectory, language):
18 """Setup the internationalization support for the given language."""
19 print "i18n.setLanguage", language
20 translation = _getTranslation(programDirectory, language)
21 fallback = _getFallbackFor(programDirectory, language)
22 if translation is None:
23 translation = fallback
24 elif fallback is not None:
25 translation.add_fallback(fallback)
26 assert translation is not None
27
28 global _translation, _language
29 _translation = translation
30 _language = language
31
32#------------------------------------------------------------------------------
33
34def getLanguage():
35 """Get the two-letter language code."""
36 underscoreIndex = _language.find("_")
37 return _language[:underscoreIndex] if underscoreIndex>0 else _language
38
39#------------------------------------------------------------------------------
40
41def xstr(key):
42 """Get the string for the given key in the current language.
43
44 If not found, the fallback language is searched. If that is not found
45 either, the key itself is returned within curly braces."""
46 return _translation.ugettext(key)
47
48#------------------------------------------------------------------------------
49
50def _getFallbackFor(programDirectory, language):
51 """Get the fallback for the given language.
52
53 If the language is English, None is returned, otherwise the English
54 language translation."""
55 if language in ["en", "en_GB"]:
56 return None
57 else:
58 return _getTranslation(programDirectory, "en")
59
60#------------------------------------------------------------------------------
61
62def _getTranslation(programDirectory, language):
63 """Get the translation for the given language."""
64 try:
65 return gettext.translation("mlx",
66 localedir = os.path.join(programDirectory,
67 "locale"),
68 languages = [language])
69 except:
70 traceback.print_exc()
71 return None
72
73#------------------------------------------------------------------------------
Note: See TracBrowser for help on using the repository browser.