source: src/mlx/i18n.py@ 1132:0d569e337b6c

python3
Last change on this file since 1132:0d569e337b6c was 928:3b16c095d166, checked in by István Váradi <ivaradi@…>, 6 years ago

Unicode handling changes (re #347).

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