Package pyjamas :: Module JSONTranslations
[hide private]
[frames] | no frames]

Source Code for Module pyjamas.JSONTranslations

  1  # Copyright (C) 2012 Kees Bos <cornelis.bos@gmail.com> 
  2  # LISENCE : Apache 2.0 or WTFPL, choose what suits your needs 
  3  # 
  4   
  5  from gettext import NullTranslations 
  6  import re 
  7  from JSONService import loads 
  8  from HTTPRequest import HTTPRequest 
  9   
 10  try: 
 11      from gettext import c2py 
 12  except ImportError: 
 13      from __pyjamas__ import JS 
14 - def c2py(plural):
15 f = None 16 JS('''eval("@{{f}}=function(n){return " + @{{plural}} + ";}")''') 17 return f
18 19
20 -class JSONTranslations(NullTranslations):
21 re_nplurals = re.compile('nplurals *= *(\d+)') 22 re_plural = re.compile('plural *= *([^;]+)') 23 base_url = None 24 domain = None 25
26 - def __init__(self, *args, **kwargs):
27 NullTranslations.__init__(self, *args, **kwargs) 28 self.new_catalog()
29
30 - def new_catalog(self, base_url=None, domain=None, lang=None):
31 self._catalog = {} 32 self.lang = lang 33 self.plural = lambda n: int(n != 1) # germanic plural by default
34
35 - def load(self, base_url=None, domain=None, lang=None, onCompletion=None, onError=None):
36 if base_url is None: 37 base_url = self.base_url 38 if domain is None: 39 domain = self.domain 40 url = base_url 41 if domain is not None and lang is not None: 42 url = "%s/%s_%s.json" % (url, domain, lang) 43 self.new_catalog(base_url, domain, lang) 44 self._onCompletion = onCompletion 45 self._onError = onError 46 HTTPRequest().asyncGet(url, self)
47
48 - def onCompletion(self, text):
49 self.parse_json(text) 50 if self._onCompletion is not None: 51 self._onCompletion(text)
52
53 - def onError(self, text, code):
54 if self._onError is not None: 55 self._onError(text, code) 56 raise RuntimeError(code)
57
58 - def onTimeout(self, text):
59 pass
60
61 - def onProgress(self, event):
62 pass
63
64 - def parse_json(self, text):
65 json = loads(text) 66 self._catalog.update(json) 67 for k, v in self._catalog[""].iteritems(): 68 k = k.lower() 69 if k == 'plural-forms': 70 self.nplurals = int(self.re_nplurals.search(v).group(1)) 71 self.plural = c2py(self.re_plural.search(v).group(1))
72
73 - def _parse(self, url):
74 self.load(url)
75
76 - def gettext(self, message):
77 tmsg = self._catalog.get(message) 78 if tmsg is None: 79 if self._fallback: 80 return self._fallback.gettext(message) 81 return message 82 return tmsg[0]
83
84 - def ngettext(self, msgid1, msgid2, n):
85 tmsg = self._catalog.get(msgid1) 86 if tmsg is None: 87 if self._fallback: 88 return self._fallback.ngettext(msgid1, msgid2, n) 89 if self.plural(n): 90 return msgid2 91 return msgid1 92 else: 93 return tmsg[self.plural(n)]
94 95 lgettext = gettext 96 lngettext = ngettext 97 ugettext = gettext 98 ungettext = ngettext
99