PageRenderTime 56ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/Python/system/gettext.py

https://bitbucket.org/cwalther/moulscript-dlanor
Python | 493 lines | 351 code | 46 blank | 96 comment | 69 complexity | c23e98940b6c9847dfe0f8cffe940ddb MD5 | raw file
Possible License(s): AGPL-1.0, GPL-3.0
  1. """Internationalization and localization support.
  2. This module provides internationalization (I18N) and localization (L10N)
  3. support for your Python programs by providing an interface to the GNU gettext
  4. message catalog library.
  5. I18N refers to the operation by which a program is made aware of multiple
  6. languages. L10N refers to the adaptation of your program, once
  7. internationalized, to the local language and cultural habits.
  8. """
  9. # This module represents the integration of work, contributions, feedback, and
  10. # suggestions from the following people:
  11. #
  12. # Martin von Loewis, who wrote the initial implementation of the underlying
  13. # C-based libintlmodule (later renamed _gettext), along with a skeletal
  14. # gettext.py implementation.
  15. #
  16. # Peter Funk, who wrote fintl.py, a fairly complete wrapper around intlmodule,
  17. # which also included a pure-Python implementation to read .mo files if
  18. # intlmodule wasn't available.
  19. #
  20. # James Henstridge, who also wrote a gettext.py module, which has some
  21. # interesting, but currently unsupported experimental features: the notion of
  22. # a Catalog class and instances, and the ability to add to a catalog file via
  23. # a Python API.
  24. #
  25. # Barry Warsaw integrated these modules, wrote the .install() API and code,
  26. # and conformed all C and Python code to Python's coding standards.
  27. #
  28. # Francois Pinard and Marc-Andre Lemburg also contributed valuably to this
  29. # module.
  30. #
  31. # J. David Ibanez implemented plural forms. Bruno Haible fixed some bugs.
  32. #
  33. # TODO:
  34. # - Lazy loading of .mo files. Currently the entire catalog is loaded into
  35. # memory, but that's probably bad for large translated programs. Instead,
  36. # the lexical sort of original strings in GNU .mo files should be exploited
  37. # to do binary searches and lazy initializations. Or you might want to use
  38. # the undocumented double-hash algorithm for .mo files with hash tables, but
  39. # you'll need to study the GNU gettext code to do this.
  40. #
  41. # - Support Solaris .mo file formats. Unfortunately, we've been unable to
  42. # find this format documented anywhere.
  43. import copy, os, re, struct, sys
  44. from errno import ENOENT
  45. __all__ = ['NullTranslations', 'GNUTranslations', 'Catalog',
  46. 'find', 'translation', 'install', 'textdomain', 'bindtextdomain',
  47. 'dgettext', 'dngettext', 'gettext', 'ngettext',
  48. ]
  49. _default_localedir = os.path.join(sys.prefix, 'share', 'locale')
  50. def test(condition, true, false):
  51. """
  52. Implements the C expression:
  53. condition ? true : false
  54. Required to correctly interpret plural forms.
  55. """
  56. if condition:
  57. return true
  58. else:
  59. return false
  60. def c2py(plural):
  61. """Gets a C expression as used in PO files for plural forms and returns a
  62. Python lambda function that implements an equivalent expression.
  63. """
  64. # Security check, allow only the "n" identifier
  65. from StringIO import StringIO
  66. import token, tokenize
  67. tokens = tokenize.generate_tokens(StringIO(plural).readline)
  68. try:
  69. danger = [x for x in tokens if x[0] == token.NAME and x[1] != 'n']
  70. except tokenize.TokenError:
  71. raise ValueError, \
  72. 'plural forms expression error, maybe unbalanced parenthesis'
  73. else:
  74. if danger:
  75. raise ValueError, 'plural forms expression could be dangerous'
  76. # Replace some C operators by their Python equivalents
  77. plural = plural.replace('&&', ' and ')
  78. plural = plural.replace('||', ' or ')
  79. expr = re.compile(r'\!([^=])')
  80. plural = expr.sub(' not \\1', plural)
  81. # Regular expression and replacement function used to transform
  82. # "a?b:c" to "test(a,b,c)".
  83. expr = re.compile(r'(.*?)\?(.*?):(.*)')
  84. def repl(x):
  85. return "test(%s, %s, %s)" % (x.group(1), x.group(2),
  86. expr.sub(repl, x.group(3)))
  87. # Code to transform the plural expression, taking care of parentheses
  88. stack = ['']
  89. for c in plural:
  90. if c == '(':
  91. stack.append('')
  92. elif c == ')':
  93. if len(stack) == 1:
  94. # Actually, we never reach this code, because unbalanced
  95. # parentheses get caught in the security check at the
  96. # beginning.
  97. raise ValueError, 'unbalanced parenthesis in plural form'
  98. s = expr.sub(repl, stack.pop())
  99. stack[-1] += '(%s)' % s
  100. else:
  101. stack[-1] += c
  102. plural = expr.sub(repl, stack.pop())
  103. return eval('lambda n: int(%s)' % plural)
  104. def _expand_lang(locale):
  105. from locale import normalize
  106. locale = normalize(locale)
  107. COMPONENT_CODESET = 1 << 0
  108. COMPONENT_TERRITORY = 1 << 1
  109. COMPONENT_MODIFIER = 1 << 2
  110. # split up the locale into its base components
  111. mask = 0
  112. pos = locale.find('@')
  113. if pos >= 0:
  114. modifier = locale[pos:]
  115. locale = locale[:pos]
  116. mask |= COMPONENT_MODIFIER
  117. else:
  118. modifier = ''
  119. pos = locale.find('.')
  120. if pos >= 0:
  121. codeset = locale[pos:]
  122. locale = locale[:pos]
  123. mask |= COMPONENT_CODESET
  124. else:
  125. codeset = ''
  126. pos = locale.find('_')
  127. if pos >= 0:
  128. territory = locale[pos:]
  129. locale = locale[:pos]
  130. mask |= COMPONENT_TERRITORY
  131. else:
  132. territory = ''
  133. language = locale
  134. ret = []
  135. for i in range(mask+1):
  136. if not (i & ~mask): # if all components for this combo exist ...
  137. val = language
  138. if i & COMPONENT_TERRITORY: val += territory
  139. if i & COMPONENT_CODESET: val += codeset
  140. if i & COMPONENT_MODIFIER: val += modifier
  141. ret.append(val)
  142. ret.reverse()
  143. return ret
  144. class NullTranslations:
  145. def __init__(self, fp=None):
  146. self._info = {}
  147. self._charset = None
  148. self._fallback = None
  149. if fp is not None:
  150. self._parse(fp)
  151. def _parse(self, fp):
  152. pass
  153. def add_fallback(self, fallback):
  154. if self._fallback:
  155. self._fallback.add_fallback(fallback)
  156. else:
  157. self._fallback = fallback
  158. def gettext(self, message):
  159. if self._fallback:
  160. return self._fallback.gettext(message)
  161. return message
  162. def ngettext(self, msgid1, msgid2, n):
  163. if self._fallback:
  164. return self._fallback.ngettext(msgid1, msgid2, n)
  165. if n == 1:
  166. return msgid1
  167. else:
  168. return msgid2
  169. def ugettext(self, message):
  170. if self._fallback:
  171. return self._fallback.ugettext(message)
  172. return unicode(message)
  173. def ungettext(self, msgid1, msgid2, n):
  174. if self._fallback:
  175. return self._fallback.ungettext(msgid1, msgid2, n)
  176. if n == 1:
  177. return unicode(msgid1)
  178. else:
  179. return unicode(msgid2)
  180. def info(self):
  181. return self._info
  182. def charset(self):
  183. return self._charset
  184. def install(self, unicode=False):
  185. import __builtin__
  186. __builtin__.__dict__['_'] = unicode and self.ugettext or self.gettext
  187. class GNUTranslations(NullTranslations):
  188. # Magic number of .mo files
  189. LE_MAGIC = 0x950412deL
  190. BE_MAGIC = 0xde120495L
  191. def _parse(self, fp):
  192. """Override this method to support alternative .mo formats."""
  193. unpack = struct.unpack
  194. filename = getattr(fp, 'name', '')
  195. # Parse the .mo file header, which consists of 5 little endian 32
  196. # bit words.
  197. self._catalog = catalog = {}
  198. self.plural = lambda n: int(n != 1) # germanic plural by default
  199. buf = fp.read()
  200. buflen = len(buf)
  201. # Are we big endian or little endian?
  202. magic = unpack('<I', buf[:4])[0]
  203. if magic == self.LE_MAGIC:
  204. version, msgcount, masteridx, transidx = unpack('<4I', buf[4:20])
  205. ii = '<II'
  206. elif magic == self.BE_MAGIC:
  207. version, msgcount, masteridx, transidx = unpack('>4I', buf[4:20])
  208. ii = '>II'
  209. else:
  210. raise IOError(0, 'Bad magic number', filename)
  211. # Now put all messages from the .mo file buffer into the catalog
  212. # dictionary.
  213. for i in xrange(0, msgcount):
  214. mlen, moff = unpack(ii, buf[masteridx:masteridx+8])
  215. mend = moff + mlen
  216. tlen, toff = unpack(ii, buf[transidx:transidx+8])
  217. tend = toff + tlen
  218. if mend < buflen and tend < buflen:
  219. msg = buf[moff:mend]
  220. tmsg = buf[toff:tend]
  221. else:
  222. raise IOError(0, 'File is corrupt', filename)
  223. # See if we're looking at GNU .mo conventions for metadata
  224. if mlen == 0:
  225. # Catalog description
  226. lastk = k = None
  227. for item in tmsg.splitlines():
  228. item = item.strip()
  229. if not item:
  230. continue
  231. if ':' in item:
  232. k, v = item.split(':', 1)
  233. k = k.strip().lower()
  234. v = v.strip()
  235. self._info[k] = v
  236. lastk = k
  237. elif lastk:
  238. self._info[lastk] += '\n' + item
  239. if k == 'content-type':
  240. self._charset = v.split('charset=')[1]
  241. elif k == 'plural-forms':
  242. v = v.split(';')
  243. plural = v[1].split('plural=')[1]
  244. self.plural = c2py(plural)
  245. # Note: we unconditionally convert both msgids and msgstrs to
  246. # Unicode using the character encoding specified in the charset
  247. # parameter of the Content-Type header. The gettext documentation
  248. # strongly encourages msgids to be us-ascii, but some appliations
  249. # require alternative encodings (e.g. Zope's ZCML and ZPT). For
  250. # traditional gettext applications, the msgid conversion will
  251. # cause no problems since us-ascii should always be a subset of
  252. # the charset encoding. We may want to fall back to 8-bit msgids
  253. # if the Unicode conversion fails.
  254. if msg.find('\x00') >= 0:
  255. # Plural forms
  256. msgid1, msgid2 = msg.split('\x00')
  257. tmsg = tmsg.split('\x00')
  258. if self._charset:
  259. msgid1 = unicode(msgid1, self._charset)
  260. tmsg = [unicode(x, self._charset) for x in tmsg]
  261. for i in range(len(tmsg)):
  262. catalog[(msgid1, i)] = tmsg[i]
  263. else:
  264. if self._charset:
  265. msg = unicode(msg, self._charset)
  266. tmsg = unicode(tmsg, self._charset)
  267. catalog[msg] = tmsg
  268. # advance to next entry in the seek tables
  269. masteridx += 8
  270. transidx += 8
  271. def gettext(self, message):
  272. missing = object()
  273. tmsg = self._catalog.get(message, missing)
  274. if tmsg is missing:
  275. if self._fallback:
  276. return self._fallback.gettext(message)
  277. return message
  278. # Encode the Unicode tmsg back to an 8-bit string, if possible
  279. if self._charset:
  280. return tmsg.encode(self._charset)
  281. return tmsg
  282. def ngettext(self, msgid1, msgid2, n):
  283. try:
  284. tmsg = self._catalog[(msgid1, self.plural(n))]
  285. if self._charset:
  286. return tmsg.encode(self._charset)
  287. return tmsg
  288. except KeyError:
  289. if self._fallback:
  290. return self._fallback.ngettext(msgid1, msgid2, n)
  291. if n == 1:
  292. return msgid1
  293. else:
  294. return msgid2
  295. def ugettext(self, message):
  296. missing = object()
  297. tmsg = self._catalog.get(message, missing)
  298. if tmsg is missing:
  299. if self._fallback:
  300. return self._fallback.ugettext(message)
  301. return unicode(message)
  302. return tmsg
  303. def ungettext(self, msgid1, msgid2, n):
  304. try:
  305. tmsg = self._catalog[(msgid1, self.plural(n))]
  306. except KeyError:
  307. if self._fallback:
  308. return self._fallback.ungettext(msgid1, msgid2, n)
  309. if n == 1:
  310. tmsg = unicode(msgid1)
  311. else:
  312. tmsg = unicode(msgid2)
  313. return tmsg
  314. # Locate a .mo file using the gettext strategy
  315. def find(domain, localedir=None, languages=None, all=0):
  316. # Get some reasonable defaults for arguments that were not supplied
  317. if localedir is None:
  318. localedir = _default_localedir
  319. if languages is None:
  320. languages = []
  321. for envar in ('LANGUAGE', 'LC_ALL', 'LC_MESSAGES', 'LANG'):
  322. val = os.environ.get(envar)
  323. if val:
  324. languages = val.split(':')
  325. break
  326. if 'C' not in languages:
  327. languages.append('C')
  328. # now normalize and expand the languages
  329. nelangs = []
  330. for lang in languages:
  331. for nelang in _expand_lang(lang):
  332. if nelang not in nelangs:
  333. nelangs.append(nelang)
  334. # select a language
  335. if all:
  336. result = []
  337. else:
  338. result = None
  339. for lang in nelangs:
  340. if lang == 'C':
  341. break
  342. mofile = os.path.join(localedir, lang, 'LC_MESSAGES', '%s.mo' % domain)
  343. if os.path.exists(mofile):
  344. if all:
  345. result.append(mofile)
  346. else:
  347. return mofile
  348. return result
  349. # a mapping between absolute .mo file path and Translation object
  350. _translations = {}
  351. def translation(domain, localedir=None, languages=None,
  352. class_=None, fallback=False):
  353. if class_ is None:
  354. class_ = GNUTranslations
  355. mofiles = find(domain, localedir, languages, all=1)
  356. if not mofiles:
  357. if fallback:
  358. return NullTranslations()
  359. raise IOError(ENOENT, 'No translation file found for domain', domain)
  360. # TBD: do we need to worry about the file pointer getting collected?
  361. # Avoid opening, reading, and parsing the .mo file after it's been done
  362. # once.
  363. result = None
  364. for mofile in mofiles:
  365. key = os.path.abspath(mofile)
  366. t = _translations.get(key)
  367. if t is None:
  368. t = _translations.setdefault(key, class_(open(mofile, 'rb')))
  369. # Copy the translation object to allow setting fallbacks.
  370. # All other instance data is shared with the cached object.
  371. t = copy.copy(t)
  372. if result is None:
  373. result = t
  374. else:
  375. result.add_fallback(t)
  376. return result
  377. def install(domain, localedir=None, unicode=False):
  378. translation(domain, localedir, fallback=True).install(unicode)
  379. # a mapping b/w domains and locale directories
  380. _localedirs = {}
  381. # current global domain, `messages' used for compatibility w/ GNU gettext
  382. _current_domain = 'messages'
  383. def textdomain(domain=None):
  384. global _current_domain
  385. if domain is not None:
  386. _current_domain = domain
  387. return _current_domain
  388. def bindtextdomain(domain, localedir=None):
  389. global _localedirs
  390. if localedir is not None:
  391. _localedirs[domain] = localedir
  392. return _localedirs.get(domain, _default_localedir)
  393. def dgettext(domain, message):
  394. try:
  395. t = translation(domain, _localedirs.get(domain, None))
  396. except IOError:
  397. return message
  398. return t.gettext(message)
  399. def dngettext(domain, msgid1, msgid2, n):
  400. try:
  401. t = translation(domain, _localedirs.get(domain, None))
  402. except IOError:
  403. if n == 1:
  404. return msgid1
  405. else:
  406. return msgid2
  407. return t.ngettext(msgid1, msgid2, n)
  408. def gettext(message):
  409. return dgettext(_current_domain, message)
  410. def ngettext(msgid1, msgid2, n):
  411. return dngettext(_current_domain, msgid1, msgid2, n)
  412. # dcgettext() has been deemed unnecessary and is not implemented.
  413. # James Henstridge's Catalog constructor from GNOME gettext. Documented usage
  414. # was:
  415. #
  416. # import gettext
  417. # cat = gettext.Catalog(PACKAGE, localedir=LOCALEDIR)
  418. # _ = cat.gettext
  419. # print _('Hello World')
  420. # The resulting catalog object currently don't support access through a
  421. # dictionary API, which was supported (but apparently unused) in GNOME
  422. # gettext.
  423. Catalog = translation