git-cola v1.9.1
[git-cola.git] / cola / i18n.py
blob38c758ee8f5644b2a2287d34b8da8c5eb255477e
1 """i18n and l10n support for git-cola"""
3 import gettext as _gettext
4 import os
5 import sys
7 from cola import compat
8 from cola import core
9 from cola import resources
10 from cola import xdg
12 _null_translation = _gettext.NullTranslations()
13 _translation = _null_translation
16 def gettext(s):
17 txt = _translation.ugettext(s)
18 if txt[-6:-4] == '@@': # handle @@verb / @@noun
19 txt = txt[:-6]
20 return txt
23 def ngettext(s, p, n):
24 return _translation.ungettext(s, p, n)
27 def N_(s):
28 return gettext(s)
31 def install(locale):
32 global _translation
33 if sys.platform == 'win32':
34 _check_win32_locale()
35 if locale:
36 compat.setenv('LANG', locale)
37 compat.setenv('LC_MESSAGES', locale)
38 _install_custom_language()
39 _gettext.textdomain('messages')
40 _translation = _gettext.translation('git-cola',
41 localedir=_get_locale_dir(),
42 fallback=True)
44 def uninstall():
45 global _translation
46 _translation = _null_translation
49 def _get_locale_dir():
50 return resources.prefix('share', 'locale')
53 def _install_custom_language():
54 """Allow a custom language to be set in ~/.config/git-cola/language"""
55 lang_file = xdg.config_home('language')
56 if not core.exists(lang_file):
57 return
58 try:
59 lang = core.read(lang_file).strip()
60 except:
61 return
62 if lang:
63 compat.setenv('LANGUAGE', lang)
66 def _check_win32_locale():
67 for i in ('LANGUAGE','LC_ALL','LC_MESSAGES','LANG'):
68 if os.environ.get(i):
69 break
70 else:
71 lang = None
72 import locale
73 try:
74 import ctypes
75 except ImportError:
76 # use only user's default locale
77 lang = locale.getdefaultlocale()[0]
78 else:
79 # using ctypes to determine all locales
80 lcid_user = ctypes.windll.kernel32.GetUserDefaultLCID()
81 lcid_system = ctypes.windll.kernel32.GetSystemDefaultLCID()
82 if lcid_user != lcid_system:
83 lcid = [lcid_user, lcid_system]
84 else:
85 lcid = [lcid_user]
86 lang = [locale.windows_locale.get(i) for i in lcid]
87 lang = ':'.join([i for i in lang if i])
88 # set lang code for gettext
89 if lang:
90 compat.setenv('LANGUAGE', lang)