| 1 | n/a | """Internationalization and localization support. |
|---|
| 2 | n/a | |
|---|
| 3 | n/a | This module provides internationalization (I18N) and localization (L10N) |
|---|
| 4 | n/a | support for your Python programs by providing an interface to the GNU gettext |
|---|
| 5 | n/a | message catalog library. |
|---|
| 6 | n/a | |
|---|
| 7 | n/a | I18N refers to the operation by which a program is made aware of multiple |
|---|
| 8 | n/a | languages. L10N refers to the adaptation of your program, once |
|---|
| 9 | n/a | internationalized, to the local language and cultural habits. |
|---|
| 10 | n/a | |
|---|
| 11 | n/a | """ |
|---|
| 12 | n/a | |
|---|
| 13 | n/a | # This module represents the integration of work, contributions, feedback, and |
|---|
| 14 | n/a | # suggestions from the following people: |
|---|
| 15 | n/a | # |
|---|
| 16 | n/a | # Martin von Loewis, who wrote the initial implementation of the underlying |
|---|
| 17 | n/a | # C-based libintlmodule (later renamed _gettext), along with a skeletal |
|---|
| 18 | n/a | # gettext.py implementation. |
|---|
| 19 | n/a | # |
|---|
| 20 | n/a | # Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule, |
|---|
| 21 | n/a | # which also included a pure-Python implementation to read .mo files if |
|---|
| 22 | n/a | # intlmodule wasn't available. |
|---|
| 23 | n/a | # |
|---|
| 24 | n/a | # James Henstridge, who also wrote a gettext.py module, which has some |
|---|
| 25 | n/a | # interesting, but currently unsupported experimental features: the notion of |
|---|
| 26 | n/a | # a Catalog class and instances, and the ability to add to a catalog file via |
|---|
| 27 | n/a | # a Python API. |
|---|
| 28 | n/a | # |
|---|
| 29 | n/a | # Barry Warsaw integrated these modules, wrote the .install() API and code, |
|---|
| 30 | n/a | # and conformed all C and Python code to Python's coding standards. |
|---|
| 31 | n/a | # |
|---|
| 32 | n/a | # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this |
|---|
| 33 | n/a | # module. |
|---|
| 34 | n/a | # |
|---|
| 35 | n/a | # J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs. |
|---|
| 36 | n/a | # |
|---|
| 37 | n/a | # TODO: |
|---|
| 38 | n/a | # - Lazy loading of .mo files. Currently the entire catalog is loaded into |
|---|
| 39 | n/a | # memory, but that's probably bad for large translated programs. Instead, |
|---|
| 40 | n/a | # the lexical sort of original strings in GNU .mo files should be exploited |
|---|
| 41 | n/a | # to do binary searches and lazy initializations. Or you might want to use |
|---|
| 42 | n/a | # the undocumented double-hash algorithm for .mo files with hash tables, but |
|---|
| 43 | n/a | # you'll need to study the GNU gettext code to do this. |
|---|
| 44 | n/a | # |
|---|
| 45 | n/a | # - Support Solaris .mo file formats. Unfortunately, we've been unable to |
|---|
| 46 | n/a | # find this format documented anywhere. |
|---|
| 47 | n/a | |
|---|
| 48 | n/a | |
|---|
| 49 | n/a | import locale, copy, io, os, re, struct, sys |
|---|
| 50 | n/a | from errno import ENOENT |
|---|
| 51 | n/a | |
|---|
| 52 | n/a | |
|---|
| 53 | n/a | __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog', |
|---|
| 54 | n/a | 'find', 'translation', 'install', 'textdomain', 'bindtextdomain', |
|---|
| 55 | n/a | 'bind_textdomain_codeset', |
|---|
| 56 | n/a | 'dgettext', 'dngettext', 'gettext', 'lgettext', 'ldgettext', |
|---|
| 57 | n/a | 'ldngettext', 'lngettext', 'ngettext', |
|---|
| 58 | n/a | ] |
|---|
| 59 | n/a | |
|---|
| 60 | n/a | _default_localedir = os.path.join(sys.base_prefix, 'share', 'locale') |
|---|
| 61 | n/a | |
|---|
| 62 | n/a | # Expression parsing for plural form selection. |
|---|
| 63 | n/a | # |
|---|
| 64 | n/a | # The gettext library supports a small subset of C syntax. The only |
|---|
| 65 | n/a | # incompatible difference is that integer literals starting with zero are |
|---|
| 66 | n/a | # decimal. |
|---|
| 67 | n/a | # |
|---|
| 68 | n/a | # https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms |
|---|
| 69 | n/a | # http://git.savannah.gnu.org/cgit/gettext.git/tree/gettext-runtime/intl/plural.y |
|---|
| 70 | n/a | |
|---|
| 71 | n/a | _token_pattern = re.compile(r""" |
|---|
| 72 | n/a | (?P<WHITESPACES>[ \t]+) | # spaces and horizontal tabs |
|---|
| 73 | n/a | (?P<NUMBER>[0-9]+\b) | # decimal integer |
|---|
| 74 | n/a | (?P<NAME>n\b) | # only n is allowed |
|---|
| 75 | n/a | (?P<PARENTHESIS>[()]) | |
|---|
| 76 | n/a | (?P<OPERATOR>[-*/%+?:]|[><!]=?|==|&&|\|\|) | # !, *, /, %, +, -, <, >, |
|---|
| 77 | n/a | # <=, >=, ==, !=, &&, ||, |
|---|
| 78 | n/a | # ? : |
|---|
| 79 | n/a | # unary and bitwise ops |
|---|
| 80 | n/a | # not allowed |
|---|
| 81 | n/a | (?P<INVALID>\w+|.) # invalid token |
|---|
| 82 | n/a | """, re.VERBOSE|re.DOTALL) |
|---|
| 83 | n/a | |
|---|
| 84 | n/a | def _tokenize(plural): |
|---|
| 85 | n/a | for mo in re.finditer(_token_pattern, plural): |
|---|
| 86 | n/a | kind = mo.lastgroup |
|---|
| 87 | n/a | if kind == 'WHITESPACES': |
|---|
| 88 | n/a | continue |
|---|
| 89 | n/a | value = mo.group(kind) |
|---|
| 90 | n/a | if kind == 'INVALID': |
|---|
| 91 | n/a | raise ValueError('invalid token in plural form: %s' % value) |
|---|
| 92 | n/a | yield value |
|---|
| 93 | n/a | yield '' |
|---|
| 94 | n/a | |
|---|
| 95 | n/a | def _error(value): |
|---|
| 96 | n/a | if value: |
|---|
| 97 | n/a | return ValueError('unexpected token in plural form: %s' % value) |
|---|
| 98 | n/a | else: |
|---|
| 99 | n/a | return ValueError('unexpected end of plural form') |
|---|
| 100 | n/a | |
|---|
| 101 | n/a | _binary_ops = ( |
|---|
| 102 | n/a | ('||',), |
|---|
| 103 | n/a | ('&&',), |
|---|
| 104 | n/a | ('==', '!='), |
|---|
| 105 | n/a | ('<', '>', '<=', '>='), |
|---|
| 106 | n/a | ('+', '-'), |
|---|
| 107 | n/a | ('*', '/', '%'), |
|---|
| 108 | n/a | ) |
|---|
| 109 | n/a | _binary_ops = {op: i for i, ops in enumerate(_binary_ops, 1) for op in ops} |
|---|
| 110 | n/a | _c2py_ops = {'||': 'or', '&&': 'and', '/': '//'} |
|---|
| 111 | n/a | |
|---|
| 112 | n/a | def _parse(tokens, priority=-1): |
|---|
| 113 | n/a | result = '' |
|---|
| 114 | n/a | nexttok = next(tokens) |
|---|
| 115 | n/a | while nexttok == '!': |
|---|
| 116 | n/a | result += 'not ' |
|---|
| 117 | n/a | nexttok = next(tokens) |
|---|
| 118 | n/a | |
|---|
| 119 | n/a | if nexttok == '(': |
|---|
| 120 | n/a | sub, nexttok = _parse(tokens) |
|---|
| 121 | n/a | result = '%s(%s)' % (result, sub) |
|---|
| 122 | n/a | if nexttok != ')': |
|---|
| 123 | n/a | raise ValueError('unbalanced parenthesis in plural form') |
|---|
| 124 | n/a | elif nexttok == 'n': |
|---|
| 125 | n/a | result = '%s%s' % (result, nexttok) |
|---|
| 126 | n/a | else: |
|---|
| 127 | n/a | try: |
|---|
| 128 | n/a | value = int(nexttok, 10) |
|---|
| 129 | n/a | except ValueError: |
|---|
| 130 | n/a | raise _error(nexttok) from None |
|---|
| 131 | n/a | result = '%s%d' % (result, value) |
|---|
| 132 | n/a | nexttok = next(tokens) |
|---|
| 133 | n/a | |
|---|
| 134 | n/a | j = 100 |
|---|
| 135 | n/a | while nexttok in _binary_ops: |
|---|
| 136 | n/a | i = _binary_ops[nexttok] |
|---|
| 137 | n/a | if i < priority: |
|---|
| 138 | n/a | break |
|---|
| 139 | n/a | # Break chained comparisons |
|---|
| 140 | n/a | if i in (3, 4) and j in (3, 4): # '==', '!=', '<', '>', '<=', '>=' |
|---|
| 141 | n/a | result = '(%s)' % result |
|---|
| 142 | n/a | # Replace some C operators by their Python equivalents |
|---|
| 143 | n/a | op = _c2py_ops.get(nexttok, nexttok) |
|---|
| 144 | n/a | right, nexttok = _parse(tokens, i + 1) |
|---|
| 145 | n/a | result = '%s %s %s' % (result, op, right) |
|---|
| 146 | n/a | j = i |
|---|
| 147 | n/a | if j == priority == 4: # '<', '>', '<=', '>=' |
|---|
| 148 | n/a | result = '(%s)' % result |
|---|
| 149 | n/a | |
|---|
| 150 | n/a | if nexttok == '?' and priority <= 0: |
|---|
| 151 | n/a | if_true, nexttok = _parse(tokens, 0) |
|---|
| 152 | n/a | if nexttok != ':': |
|---|
| 153 | n/a | raise _error(nexttok) |
|---|
| 154 | n/a | if_false, nexttok = _parse(tokens) |
|---|
| 155 | n/a | result = '%s if %s else %s' % (if_true, result, if_false) |
|---|
| 156 | n/a | if priority == 0: |
|---|
| 157 | n/a | result = '(%s)' % result |
|---|
| 158 | n/a | |
|---|
| 159 | n/a | return result, nexttok |
|---|
| 160 | n/a | |
|---|
| 161 | n/a | def _as_int(n): |
|---|
| 162 | n/a | try: |
|---|
| 163 | n/a | i = round(n) |
|---|
| 164 | n/a | except TypeError: |
|---|
| 165 | n/a | raise TypeError('Plural value must be an integer, got %s' % |
|---|
| 166 | n/a | (n.__class__.__name__,)) from None |
|---|
| 167 | n/a | return n |
|---|
| 168 | n/a | |
|---|
| 169 | n/a | def c2py(plural): |
|---|
| 170 | n/a | """Gets a C expression as used in PO files for plural forms and returns a |
|---|
| 171 | n/a | Python function that implements an equivalent expression. |
|---|
| 172 | n/a | """ |
|---|
| 173 | n/a | |
|---|
| 174 | n/a | if len(plural) > 1000: |
|---|
| 175 | n/a | raise ValueError('plural form expression is too long') |
|---|
| 176 | n/a | try: |
|---|
| 177 | n/a | result, nexttok = _parse(_tokenize(plural)) |
|---|
| 178 | n/a | if nexttok: |
|---|
| 179 | n/a | raise _error(nexttok) |
|---|
| 180 | n/a | |
|---|
| 181 | n/a | depth = 0 |
|---|
| 182 | n/a | for c in result: |
|---|
| 183 | n/a | if c == '(': |
|---|
| 184 | n/a | depth += 1 |
|---|
| 185 | n/a | if depth > 20: |
|---|
| 186 | n/a | # Python compiler limit is about 90. |
|---|
| 187 | n/a | # The most complex example has 2. |
|---|
| 188 | n/a | raise ValueError('plural form expression is too complex') |
|---|
| 189 | n/a | elif c == ')': |
|---|
| 190 | n/a | depth -= 1 |
|---|
| 191 | n/a | |
|---|
| 192 | n/a | ns = {'_as_int': _as_int} |
|---|
| 193 | n/a | exec('''if True: |
|---|
| 194 | n/a | def func(n): |
|---|
| 195 | n/a | if not isinstance(n, int): |
|---|
| 196 | n/a | n = _as_int(n) |
|---|
| 197 | n/a | return int(%s) |
|---|
| 198 | n/a | ''' % result, ns) |
|---|
| 199 | n/a | return ns['func'] |
|---|
| 200 | n/a | except RecursionError: |
|---|
| 201 | n/a | # Recursion error can be raised in _parse() or exec(). |
|---|
| 202 | n/a | raise ValueError('plural form expression is too complex') |
|---|
| 203 | n/a | |
|---|
| 204 | n/a | |
|---|
| 205 | n/a | def _expand_lang(loc): |
|---|
| 206 | n/a | loc = locale.normalize(loc) |
|---|
| 207 | n/a | COMPONENT_CODESET = 1 << 0 |
|---|
| 208 | n/a | COMPONENT_TERRITORY = 1 << 1 |
|---|
| 209 | n/a | COMPONENT_MODIFIER = 1 << 2 |
|---|
| 210 | n/a | # split up the locale into its base components |
|---|
| 211 | n/a | mask = 0 |
|---|
| 212 | n/a | pos = loc.find('@') |
|---|
| 213 | n/a | if pos >= 0: |
|---|
| 214 | n/a | modifier = loc[pos:] |
|---|
| 215 | n/a | loc = loc[:pos] |
|---|
| 216 | n/a | mask |= COMPONENT_MODIFIER |
|---|
| 217 | n/a | else: |
|---|
| 218 | n/a | modifier = '' |
|---|
| 219 | n/a | pos = loc.find('.') |
|---|
| 220 | n/a | if pos >= 0: |
|---|
| 221 | n/a | codeset = loc[pos:] |
|---|
| 222 | n/a | loc = loc[:pos] |
|---|
| 223 | n/a | mask |= COMPONENT_CODESET |
|---|
| 224 | n/a | else: |
|---|
| 225 | n/a | codeset = '' |
|---|
| 226 | n/a | pos = loc.find('_') |
|---|
| 227 | n/a | if pos >= 0: |
|---|
| 228 | n/a | territory = loc[pos:] |
|---|
| 229 | n/a | loc = loc[:pos] |
|---|
| 230 | n/a | mask |= COMPONENT_TERRITORY |
|---|
| 231 | n/a | else: |
|---|
| 232 | n/a | territory = '' |
|---|
| 233 | n/a | language = loc |
|---|
| 234 | n/a | ret = [] |
|---|
| 235 | n/a | for i in range(mask+1): |
|---|
| 236 | n/a | if not (i & ~mask): # if all components for this combo exist ... |
|---|
| 237 | n/a | val = language |
|---|
| 238 | n/a | if i & COMPONENT_TERRITORY: val += territory |
|---|
| 239 | n/a | if i & COMPONENT_CODESET: val += codeset |
|---|
| 240 | n/a | if i & COMPONENT_MODIFIER: val += modifier |
|---|
| 241 | n/a | ret.append(val) |
|---|
| 242 | n/a | ret.reverse() |
|---|
| 243 | n/a | return ret |
|---|
| 244 | n/a | |
|---|
| 245 | n/a | |
|---|
| 246 | n/a | |
|---|
| 247 | n/a | class NullTranslations: |
|---|
| 248 | n/a | def __init__(self, fp=None): |
|---|
| 249 | n/a | self._info = {} |
|---|
| 250 | n/a | self._charset = None |
|---|
| 251 | n/a | self._output_charset = None |
|---|
| 252 | n/a | self._fallback = None |
|---|
| 253 | n/a | if fp is not None: |
|---|
| 254 | n/a | self._parse(fp) |
|---|
| 255 | n/a | |
|---|
| 256 | n/a | def _parse(self, fp): |
|---|
| 257 | n/a | pass |
|---|
| 258 | n/a | |
|---|
| 259 | n/a | def add_fallback(self, fallback): |
|---|
| 260 | n/a | if self._fallback: |
|---|
| 261 | n/a | self._fallback.add_fallback(fallback) |
|---|
| 262 | n/a | else: |
|---|
| 263 | n/a | self._fallback = fallback |
|---|
| 264 | n/a | |
|---|
| 265 | n/a | def gettext(self, message): |
|---|
| 266 | n/a | if self._fallback: |
|---|
| 267 | n/a | return self._fallback.gettext(message) |
|---|
| 268 | n/a | return message |
|---|
| 269 | n/a | |
|---|
| 270 | n/a | def lgettext(self, message): |
|---|
| 271 | n/a | if self._fallback: |
|---|
| 272 | n/a | return self._fallback.lgettext(message) |
|---|
| 273 | n/a | return message |
|---|
| 274 | n/a | |
|---|
| 275 | n/a | def ngettext(self, msgid1, msgid2, n): |
|---|
| 276 | n/a | if self._fallback: |
|---|
| 277 | n/a | return self._fallback.ngettext(msgid1, msgid2, n) |
|---|
| 278 | n/a | if n == 1: |
|---|
| 279 | n/a | return msgid1 |
|---|
| 280 | n/a | else: |
|---|
| 281 | n/a | return msgid2 |
|---|
| 282 | n/a | |
|---|
| 283 | n/a | def lngettext(self, msgid1, msgid2, n): |
|---|
| 284 | n/a | if self._fallback: |
|---|
| 285 | n/a | return self._fallback.lngettext(msgid1, msgid2, n) |
|---|
| 286 | n/a | if n == 1: |
|---|
| 287 | n/a | return msgid1 |
|---|
| 288 | n/a | else: |
|---|
| 289 | n/a | return msgid2 |
|---|
| 290 | n/a | |
|---|
| 291 | n/a | def info(self): |
|---|
| 292 | n/a | return self._info |
|---|
| 293 | n/a | |
|---|
| 294 | n/a | def charset(self): |
|---|
| 295 | n/a | return self._charset |
|---|
| 296 | n/a | |
|---|
| 297 | n/a | def output_charset(self): |
|---|
| 298 | n/a | return self._output_charset |
|---|
| 299 | n/a | |
|---|
| 300 | n/a | def set_output_charset(self, charset): |
|---|
| 301 | n/a | self._output_charset = charset |
|---|
| 302 | n/a | |
|---|
| 303 | n/a | def install(self, names=None): |
|---|
| 304 | n/a | import builtins |
|---|
| 305 | n/a | builtins.__dict__['_'] = self.gettext |
|---|
| 306 | n/a | if hasattr(names, "__contains__"): |
|---|
| 307 | n/a | if "gettext" in names: |
|---|
| 308 | n/a | builtins.__dict__['gettext'] = builtins.__dict__['_'] |
|---|
| 309 | n/a | if "ngettext" in names: |
|---|
| 310 | n/a | builtins.__dict__['ngettext'] = self.ngettext |
|---|
| 311 | n/a | if "lgettext" in names: |
|---|
| 312 | n/a | builtins.__dict__['lgettext'] = self.lgettext |
|---|
| 313 | n/a | if "lngettext" in names: |
|---|
| 314 | n/a | builtins.__dict__['lngettext'] = self.lngettext |
|---|
| 315 | n/a | |
|---|
| 316 | n/a | |
|---|
| 317 | n/a | class GNUTranslations(NullTranslations): |
|---|
| 318 | n/a | # Magic number of .mo files |
|---|
| 319 | n/a | LE_MAGIC = 0x950412de |
|---|
| 320 | n/a | BE_MAGIC = 0xde120495 |
|---|
| 321 | n/a | |
|---|
| 322 | n/a | # Acceptable .mo versions |
|---|
| 323 | n/a | VERSIONS = (0, 1) |
|---|
| 324 | n/a | |
|---|
| 325 | n/a | def _get_versions(self, version): |
|---|
| 326 | n/a | """Returns a tuple of major version, minor version""" |
|---|
| 327 | n/a | return (version >> 16, version & 0xffff) |
|---|
| 328 | n/a | |
|---|
| 329 | n/a | def _parse(self, fp): |
|---|
| 330 | n/a | """Override this method to support alternative .mo formats.""" |
|---|
| 331 | n/a | unpack = struct.unpack |
|---|
| 332 | n/a | filename = getattr(fp, 'name', '') |
|---|
| 333 | n/a | # Parse the .mo file header, which consists of 5 little endian 32 |
|---|
| 334 | n/a | # bit words. |
|---|
| 335 | n/a | self._catalog = catalog = {} |
|---|
| 336 | n/a | self.plural = lambda n: int(n != 1) # germanic plural by default |
|---|
| 337 | n/a | buf = fp.read() |
|---|
| 338 | n/a | buflen = len(buf) |
|---|
| 339 | n/a | # Are we big endian or little endian? |
|---|
| 340 | n/a | magic = unpack('<I', buf[:4])[0] |
|---|
| 341 | n/a | if magic == self.LE_MAGIC: |
|---|
| 342 | n/a | version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20]) |
|---|
| 343 | n/a | ii = '<II' |
|---|
| 344 | n/a | elif magic == self.BE_MAGIC: |
|---|
| 345 | n/a | version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20]) |
|---|
| 346 | n/a | ii = '>II' |
|---|
| 347 | n/a | else: |
|---|
| 348 | n/a | raise OSError(0, 'Bad magic number', filename) |
|---|
| 349 | n/a | |
|---|
| 350 | n/a | major_version, minor_version = self._get_versions(version) |
|---|
| 351 | n/a | |
|---|
| 352 | n/a | if major_version not in self.VERSIONS: |
|---|
| 353 | n/a | raise OSError(0, 'Bad version number ' + str(major_version), filename) |
|---|
| 354 | n/a | |
|---|
| 355 | n/a | # Now put all messages from the .mo file buffer into the catalog |
|---|
| 356 | n/a | # dictionary. |
|---|
| 357 | n/a | for i in range(0, msgcount): |
|---|
| 358 | n/a | mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) |
|---|
| 359 | n/a | mend = moff + mlen |
|---|
| 360 | n/a | tlen, toff = unpack(ii, buf[transidx:transidx+8]) |
|---|
| 361 | n/a | tend = toff + tlen |
|---|
| 362 | n/a | if mend < buflen and tend < buflen: |
|---|
| 363 | n/a | msg = buf[moff:mend] |
|---|
| 364 | n/a | tmsg = buf[toff:tend] |
|---|
| 365 | n/a | else: |
|---|
| 366 | n/a | raise OSError(0, 'File is corrupt', filename) |
|---|
| 367 | n/a | # See if we're looking at GNU .mo conventions for metadata |
|---|
| 368 | n/a | if mlen == 0: |
|---|
| 369 | n/a | # Catalog description |
|---|
| 370 | n/a | lastk = None |
|---|
| 371 | n/a | for b_item in tmsg.split('\n'.encode("ascii")): |
|---|
| 372 | n/a | item = b_item.decode().strip() |
|---|
| 373 | n/a | if not item: |
|---|
| 374 | n/a | continue |
|---|
| 375 | n/a | k = v = None |
|---|
| 376 | n/a | if ':' in item: |
|---|
| 377 | n/a | k, v = item.split(':', 1) |
|---|
| 378 | n/a | k = k.strip().lower() |
|---|
| 379 | n/a | v = v.strip() |
|---|
| 380 | n/a | self._info[k] = v |
|---|
| 381 | n/a | lastk = k |
|---|
| 382 | n/a | elif lastk: |
|---|
| 383 | n/a | self._info[lastk] += '\n' + item |
|---|
| 384 | n/a | if k == 'content-type': |
|---|
| 385 | n/a | self._charset = v.split('charset=')[1] |
|---|
| 386 | n/a | elif k == 'plural-forms': |
|---|
| 387 | n/a | v = v.split(';') |
|---|
| 388 | n/a | plural = v[1].split('plural=')[1] |
|---|
| 389 | n/a | self.plural = c2py(plural) |
|---|
| 390 | n/a | # Note: we unconditionally convert both msgids and msgstrs to |
|---|
| 391 | n/a | # Unicode using the character encoding specified in the charset |
|---|
| 392 | n/a | # parameter of the Content-Type header. The gettext documentation |
|---|
| 393 | n/a | # strongly encourages msgids to be us-ascii, but some applications |
|---|
| 394 | n/a | # require alternative encodings (e.g. Zope's ZCML and ZPT). For |
|---|
| 395 | n/a | # traditional gettext applications, the msgid conversion will |
|---|
| 396 | n/a | # cause no problems since us-ascii should always be a subset of |
|---|
| 397 | n/a | # the charset encoding. We may want to fall back to 8-bit msgids |
|---|
| 398 | n/a | # if the Unicode conversion fails. |
|---|
| 399 | n/a | charset = self._charset or 'ascii' |
|---|
| 400 | n/a | if b'\x00' in msg: |
|---|
| 401 | n/a | # Plural forms |
|---|
| 402 | n/a | msgid1, msgid2 = msg.split(b'\x00') |
|---|
| 403 | n/a | tmsg = tmsg.split(b'\x00') |
|---|
| 404 | n/a | msgid1 = str(msgid1, charset) |
|---|
| 405 | n/a | for i, x in enumerate(tmsg): |
|---|
| 406 | n/a | catalog[(msgid1, i)] = str(x, charset) |
|---|
| 407 | n/a | else: |
|---|
| 408 | n/a | catalog[str(msg, charset)] = str(tmsg, charset) |
|---|
| 409 | n/a | # advance to next entry in the seek tables |
|---|
| 410 | n/a | masteridx += 8 |
|---|
| 411 | n/a | transidx += 8 |
|---|
| 412 | n/a | |
|---|
| 413 | n/a | def lgettext(self, message): |
|---|
| 414 | n/a | missing = object() |
|---|
| 415 | n/a | tmsg = self._catalog.get(message, missing) |
|---|
| 416 | n/a | if tmsg is missing: |
|---|
| 417 | n/a | if self._fallback: |
|---|
| 418 | n/a | return self._fallback.lgettext(message) |
|---|
| 419 | n/a | return message |
|---|
| 420 | n/a | if self._output_charset: |
|---|
| 421 | n/a | return tmsg.encode(self._output_charset) |
|---|
| 422 | n/a | return tmsg.encode(locale.getpreferredencoding()) |
|---|
| 423 | n/a | |
|---|
| 424 | n/a | def lngettext(self, msgid1, msgid2, n): |
|---|
| 425 | n/a | try: |
|---|
| 426 | n/a | tmsg = self._catalog[(msgid1, self.plural(n))] |
|---|
| 427 | n/a | if self._output_charset: |
|---|
| 428 | n/a | return tmsg.encode(self._output_charset) |
|---|
| 429 | n/a | return tmsg.encode(locale.getpreferredencoding()) |
|---|
| 430 | n/a | except KeyError: |
|---|
| 431 | n/a | if self._fallback: |
|---|
| 432 | n/a | return self._fallback.lngettext(msgid1, msgid2, n) |
|---|
| 433 | n/a | if n == 1: |
|---|
| 434 | n/a | return msgid1 |
|---|
| 435 | n/a | else: |
|---|
| 436 | n/a | return msgid2 |
|---|
| 437 | n/a | |
|---|
| 438 | n/a | def gettext(self, message): |
|---|
| 439 | n/a | missing = object() |
|---|
| 440 | n/a | tmsg = self._catalog.get(message, missing) |
|---|
| 441 | n/a | if tmsg is missing: |
|---|
| 442 | n/a | if self._fallback: |
|---|
| 443 | n/a | return self._fallback.gettext(message) |
|---|
| 444 | n/a | return message |
|---|
| 445 | n/a | return tmsg |
|---|
| 446 | n/a | |
|---|
| 447 | n/a | def ngettext(self, msgid1, msgid2, n): |
|---|
| 448 | n/a | try: |
|---|
| 449 | n/a | tmsg = self._catalog[(msgid1, self.plural(n))] |
|---|
| 450 | n/a | except KeyError: |
|---|
| 451 | n/a | if self._fallback: |
|---|
| 452 | n/a | return self._fallback.ngettext(msgid1, msgid2, n) |
|---|
| 453 | n/a | if n == 1: |
|---|
| 454 | n/a | tmsg = msgid1 |
|---|
| 455 | n/a | else: |
|---|
| 456 | n/a | tmsg = msgid2 |
|---|
| 457 | n/a | return tmsg |
|---|
| 458 | n/a | |
|---|
| 459 | n/a | |
|---|
| 460 | n/a | # Locate a .mo file using the gettext strategy |
|---|
| 461 | n/a | def find(domain, localedir=None, languages=None, all=False): |
|---|
| 462 | n/a | # Get some reasonable defaults for arguments that were not supplied |
|---|
| 463 | n/a | if localedir is None: |
|---|
| 464 | n/a | localedir = _default_localedir |
|---|
| 465 | n/a | if languages is None: |
|---|
| 466 | n/a | languages = [] |
|---|
| 467 | n/a | for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'): |
|---|
| 468 | n/a | val = os.environ.get(envar) |
|---|
| 469 | n/a | if val: |
|---|
| 470 | n/a | languages = val.split(':') |
|---|
| 471 | n/a | break |
|---|
| 472 | n/a | if 'C' not in languages: |
|---|
| 473 | n/a | languages.append('C') |
|---|
| 474 | n/a | # now normalize and expand the languages |
|---|
| 475 | n/a | nelangs = [] |
|---|
| 476 | n/a | for lang in languages: |
|---|
| 477 | n/a | for nelang in _expand_lang(lang): |
|---|
| 478 | n/a | if nelang not in nelangs: |
|---|
| 479 | n/a | nelangs.append(nelang) |
|---|
| 480 | n/a | # select a language |
|---|
| 481 | n/a | if all: |
|---|
| 482 | n/a | result = [] |
|---|
| 483 | n/a | else: |
|---|
| 484 | n/a | result = None |
|---|
| 485 | n/a | for lang in nelangs: |
|---|
| 486 | n/a | if lang == 'C': |
|---|
| 487 | n/a | break |
|---|
| 488 | n/a | mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain) |
|---|
| 489 | n/a | if os.path.exists(mofile): |
|---|
| 490 | n/a | if all: |
|---|
| 491 | n/a | result.append(mofile) |
|---|
| 492 | n/a | else: |
|---|
| 493 | n/a | return mofile |
|---|
| 494 | n/a | return result |
|---|
| 495 | n/a | |
|---|
| 496 | n/a | |
|---|
| 497 | n/a | |
|---|
| 498 | n/a | # a mapping between absolute .mo file path and Translation object |
|---|
| 499 | n/a | _translations = {} |
|---|
| 500 | n/a | |
|---|
| 501 | n/a | def translation(domain, localedir=None, languages=None, |
|---|
| 502 | n/a | class_=None, fallback=False, codeset=None): |
|---|
| 503 | n/a | if class_ is None: |
|---|
| 504 | n/a | class_ = GNUTranslations |
|---|
| 505 | n/a | mofiles = find(domain, localedir, languages, all=True) |
|---|
| 506 | n/a | if not mofiles: |
|---|
| 507 | n/a | if fallback: |
|---|
| 508 | n/a | return NullTranslations() |
|---|
| 509 | n/a | raise OSError(ENOENT, 'No translation file found for domain', domain) |
|---|
| 510 | n/a | # Avoid opening, reading, and parsing the .mo file after it's been done |
|---|
| 511 | n/a | # once. |
|---|
| 512 | n/a | result = None |
|---|
| 513 | n/a | for mofile in mofiles: |
|---|
| 514 | n/a | key = (class_, os.path.abspath(mofile)) |
|---|
| 515 | n/a | t = _translations.get(key) |
|---|
| 516 | n/a | if t is None: |
|---|
| 517 | n/a | with open(mofile, 'rb') as fp: |
|---|
| 518 | n/a | t = _translations.setdefault(key, class_(fp)) |
|---|
| 519 | n/a | # Copy the translation object to allow setting fallbacks and |
|---|
| 520 | n/a | # output charset. All other instance data is shared with the |
|---|
| 521 | n/a | # cached object. |
|---|
| 522 | n/a | t = copy.copy(t) |
|---|
| 523 | n/a | if codeset: |
|---|
| 524 | n/a | t.set_output_charset(codeset) |
|---|
| 525 | n/a | if result is None: |
|---|
| 526 | n/a | result = t |
|---|
| 527 | n/a | else: |
|---|
| 528 | n/a | result.add_fallback(t) |
|---|
| 529 | n/a | return result |
|---|
| 530 | n/a | |
|---|
| 531 | n/a | |
|---|
| 532 | n/a | def install(domain, localedir=None, codeset=None, names=None): |
|---|
| 533 | n/a | t = translation(domain, localedir, fallback=True, codeset=codeset) |
|---|
| 534 | n/a | t.install(names) |
|---|
| 535 | n/a | |
|---|
| 536 | n/a | |
|---|
| 537 | n/a | |
|---|
| 538 | n/a | # a mapping b/w domains and locale directories |
|---|
| 539 | n/a | _localedirs = {} |
|---|
| 540 | n/a | # a mapping b/w domains and codesets |
|---|
| 541 | n/a | _localecodesets = {} |
|---|
| 542 | n/a | # current global domain, `messages' used for compatibility w/ GNU gettext |
|---|
| 543 | n/a | _current_domain = 'messages' |
|---|
| 544 | n/a | |
|---|
| 545 | n/a | |
|---|
| 546 | n/a | def textdomain(domain=None): |
|---|
| 547 | n/a | global _current_domain |
|---|
| 548 | n/a | if domain is not None: |
|---|
| 549 | n/a | _current_domain = domain |
|---|
| 550 | n/a | return _current_domain |
|---|
| 551 | n/a | |
|---|
| 552 | n/a | |
|---|
| 553 | n/a | def bindtextdomain(domain, localedir=None): |
|---|
| 554 | n/a | global _localedirs |
|---|
| 555 | n/a | if localedir is not None: |
|---|
| 556 | n/a | _localedirs[domain] = localedir |
|---|
| 557 | n/a | return _localedirs.get(domain, _default_localedir) |
|---|
| 558 | n/a | |
|---|
| 559 | n/a | |
|---|
| 560 | n/a | def bind_textdomain_codeset(domain, codeset=None): |
|---|
| 561 | n/a | global _localecodesets |
|---|
| 562 | n/a | if codeset is not None: |
|---|
| 563 | n/a | _localecodesets[domain] = codeset |
|---|
| 564 | n/a | return _localecodesets.get(domain) |
|---|
| 565 | n/a | |
|---|
| 566 | n/a | |
|---|
| 567 | n/a | def dgettext(domain, message): |
|---|
| 568 | n/a | try: |
|---|
| 569 | n/a | t = translation(domain, _localedirs.get(domain, None), |
|---|
| 570 | n/a | codeset=_localecodesets.get(domain)) |
|---|
| 571 | n/a | except OSError: |
|---|
| 572 | n/a | return message |
|---|
| 573 | n/a | return t.gettext(message) |
|---|
| 574 | n/a | |
|---|
| 575 | n/a | def ldgettext(domain, message): |
|---|
| 576 | n/a | try: |
|---|
| 577 | n/a | t = translation(domain, _localedirs.get(domain, None), |
|---|
| 578 | n/a | codeset=_localecodesets.get(domain)) |
|---|
| 579 | n/a | except OSError: |
|---|
| 580 | n/a | return message |
|---|
| 581 | n/a | return t.lgettext(message) |
|---|
| 582 | n/a | |
|---|
| 583 | n/a | def dngettext(domain, msgid1, msgid2, n): |
|---|
| 584 | n/a | try: |
|---|
| 585 | n/a | t = translation(domain, _localedirs.get(domain, None), |
|---|
| 586 | n/a | codeset=_localecodesets.get(domain)) |
|---|
| 587 | n/a | except OSError: |
|---|
| 588 | n/a | if n == 1: |
|---|
| 589 | n/a | return msgid1 |
|---|
| 590 | n/a | else: |
|---|
| 591 | n/a | return msgid2 |
|---|
| 592 | n/a | return t.ngettext(msgid1, msgid2, n) |
|---|
| 593 | n/a | |
|---|
| 594 | n/a | def ldngettext(domain, msgid1, msgid2, n): |
|---|
| 595 | n/a | try: |
|---|
| 596 | n/a | t = translation(domain, _localedirs.get(domain, None), |
|---|
| 597 | n/a | codeset=_localecodesets.get(domain)) |
|---|
| 598 | n/a | except OSError: |
|---|
| 599 | n/a | if n == 1: |
|---|
| 600 | n/a | return msgid1 |
|---|
| 601 | n/a | else: |
|---|
| 602 | n/a | return msgid2 |
|---|
| 603 | n/a | return t.lngettext(msgid1, msgid2, n) |
|---|
| 604 | n/a | |
|---|
| 605 | n/a | def gettext(message): |
|---|
| 606 | n/a | return dgettext(_current_domain, message) |
|---|
| 607 | n/a | |
|---|
| 608 | n/a | def lgettext(message): |
|---|
| 609 | n/a | return ldgettext(_current_domain, message) |
|---|
| 610 | n/a | |
|---|
| 611 | n/a | def ngettext(msgid1, msgid2, n): |
|---|
| 612 | n/a | return dngettext(_current_domain, msgid1, msgid2, n) |
|---|
| 613 | n/a | |
|---|
| 614 | n/a | def lngettext(msgid1, msgid2, n): |
|---|
| 615 | n/a | return ldngettext(_current_domain, msgid1, msgid2, n) |
|---|
| 616 | n/a | |
|---|
| 617 | n/a | # dcgettext() has been deemed unnecessary and is not implemented. |
|---|
| 618 | n/a | |
|---|
| 619 | n/a | # James Henstridge's Catalog constructor from GNOME gettext. Documented usage |
|---|
| 620 | n/a | # was: |
|---|
| 621 | n/a | # |
|---|
| 622 | n/a | # import gettext |
|---|
| 623 | n/a | # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR) |
|---|
| 624 | n/a | # _ = cat.gettext |
|---|
| 625 | n/a | # print _('Hello World') |
|---|
| 626 | n/a | |
|---|
| 627 | n/a | # The resulting catalog object currently don't support access through a |
|---|
| 628 | n/a | # dictionary API, which was supported (but apparently unused) in GNOME |
|---|
| 629 | n/a | # gettext. |
|---|
| 630 | n/a | |
|---|
| 631 | n/a | Catalog = translation |
|---|