git-cola v2.11
[git-cola.git] / cola / i18n.py
blob1d7443b7b9284407eaa4e863ccfea933186f5f06
1 """i18n and l10n support for git-cola"""
2 from __future__ import division, absolute_import, unicode_literals
4 import gettext as _gettext
5 import os
6 import sys
8 from . import compat
9 from . import core
10 from . import resources
12 _null_translation = _gettext.NullTranslations()
13 _translation = _null_translation
16 def gettext(s):
17 try:
18 txt = _translation.ugettext(s)
19 except AttributeError:
20 # Python 3 compat
21 _translation.ugettext = _translation.gettext
22 txt = _translation.gettext(s)
23 if txt[-6:-4] == '@@': # handle @@verb / @@noun
24 txt = txt[:-6]
25 return txt
28 def ngettext(s, p, n):
29 try:
30 txt = _translation.ungettext(s, p, n)
31 except AttributeError:
32 # Python 3 compat
33 _translation.ungettext = _translation.ngettext
34 txt = _translation.ngettext(s, p, n)
35 return txt
38 def N_(s):
39 return gettext(s)
42 def install(locale):
43 global _translation
44 if sys.platform == 'win32':
45 _check_win32_locale()
46 if locale:
47 compat.setenv('LANGUAGE', locale)
48 compat.setenv('LANG', locale)
49 compat.setenv('LC_MESSAGES', locale)
50 _install_custom_language()
51 _gettext.textdomain('messages')
52 _translation = _gettext.translation('git-cola',
53 localedir=_get_locale_dir(),
54 fallback=True)
57 def uninstall():
58 global _translation
59 _translation = _null_translation
62 def _get_locale_dir():
63 return resources.prefix('share', 'locale')
66 def _install_custom_language():
67 """Allow a custom language to be set in ~/.config/git-cola/language"""
68 lang_file = resources.config_home('language')
69 if not core.exists(lang_file):
70 return
71 try:
72 lang = core.read(lang_file).strip()
73 except:
74 return
75 if lang:
76 compat.setenv('LANGUAGE', lang)
79 def _check_win32_locale():
80 for i in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
81 if os.environ.get(i):
82 break
83 else:
84 lang = None
85 import locale
86 try:
87 import ctypes
88 except ImportError:
89 # use only user's default locale
90 lang = locale.getdefaultlocale()[0]
91 else:
92 # using ctypes to determine all locales
93 lcid_user = ctypes.windll.kernel32.GetUserDefaultLCID()
94 lcid_system = ctypes.windll.kernel32.GetSystemDefaultLCID()
95 if lcid_user != lcid_system:
96 lcid = [lcid_user, lcid_system]
97 else:
98 lcid = [lcid_user]
99 lang = [locale.windows_locale.get(i) for i in lcid]
100 lang = ':'.join([i for i in lang if i])
101 # set lang code for gettext
102 if lang:
103 compat.setenv('LANGUAGE', lang)