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