root/trunk/dabo/dLocalize.py

Revision 4379, 4.6 kB (checked in by nate, 4 months ago)

Added "English_United States" to language aliases. Not sure if this is the correct way to handle this, but it get me working for now.

  • Property svn:eol-style set to native
Line 
1 import sys
2 import locale
3 import os
4 import gettext
5 import warnings
6 import dabo
7
8
9 _defaultLanguage, _defaultEncoding = locale.getlocale()
10
11 if _defaultLanguage is None:
12     _defaultLanguage = "en"
13
14 if _defaultEncoding is None:
15     _defaultEncoding = "utf-8"
16
17 _domains = {}
18 _currentTrans = None
19
20 _languageAliases = {"english": "en", "English_United States":"en",
21         "spanish": "es", "espanol": "es", "español": "es",
22         "french": "fr", "francais": "fr", "français": "fr",
23         "german": "de", "deutsch": "de",
24         "italian": "it", "italiano": "it",
25         "portuguese": "pt", "portuguése": "pt",
26         "russian": "ru"}
27
28 def _(s):
29     """Return the localized translation of s, or s if translation not possible."""
30     if _currentTrans is not None:
31         return _currentTrans(s)
32     return s
33
34
35 def n_(s):
36     return s
37
38
39 def install(domain="dabo", localedir=None, unicode_mo=True):
40     """Install the gettext translation service for the passed domain.
41
42     Either Dabo will be the only domain, or Dabo will be the fallback for a
43   different domain that the user's application set up.
44     """
45     global _domains, _defaultLanguage, _defaultEncoding
46
47     if localedir is None:
48         if domain != "dabo":
49             raise ValueError, "Must send your application's localedir explicitly."
50         localedir = getDaboLocaleDir()
51     _domains[domain] = localedir
52     #gettext.install(domain, localedir, unicode=unicode_mo)  ## No, don't globally bind _
53     setLanguage(_defaultLanguage, _defaultEncoding)
54
55
56 def isValidDomain(domain, localedir):
57     """Return True if the localedir appears to contain translations for the domain."""
58     return bool(gettext.find(domain, localedir, all=True))
59
60
61 def setLanguage(lang=None, charset=None):
62     """Change the language that strings get translated to, for all installed domains."""
63     global _domains, _currentTrans
64
65     lang = _languageAliases.get(lang, lang)
66
67     if lang is not None and isinstance(lang, basestring):
68         lang = [lang]
69
70     daboTranslation = None
71     daboLocaleDir = _domains.get("dabo", None)
72     if daboLocaleDir:
73         daboTranslation = gettext.translation("dabo", daboLocaleDir, languages=lang, codeset=charset)
74 #       daboTranslation.install()  ## No, don't globally bind _
75         _currentTrans = daboTranslation.ugettext
76
77     for domain, localedir in _domains.items():
78         if domain == "dabo":
79             continue  ## already handled separately above
80         try:
81             translation = gettext.translation(domain, localedir, languages=lang, codeset=charset)
82         except IOError:
83             raise IOError, "No translation found for domain '%s' and language %s." % (domain, lang)
84         if daboTranslation:
85             translation.add_fallback(daboTranslation)
86 #       translation.install()  ## No, don't globally bind _
87         _currentTrans = translation.ugettext
88
89
90 def getDaboLocaleDir():
91     localeDirNames = ("dabo.locale", "locale")
92     for localeDirName in localeDirNames:
93         localeDir = os.path.join(os.path.split(dabo.__file__)[0], localeDirName)
94         if not os.path.isdir(localeDir):
95             # Frozen app?
96             # First need to find the directory that contains the executable. On the Mac,
97             # it might be a directory at a lower level than dabo itself.
98             startupDir = localeDir
99             while startupDir:
100                 newDir = os.path.split(startupDir)[0]
101                 if newDir == startupDir:
102                     # At the root dir
103                     break
104                 startupDir = newDir
105                 candidate = os.path.join(startupDir, localeDirName)
106                 if os.path.isdir(candidate):
107                     break
108             if os.path.isdir(candidate):
109                 localeDir = candidate
110                 break
111     return localeDir
112
113
114 if __name__ == "__main__":
115     install()
116     print "sys.getdefaultencoding():", sys.getdefaultencoding()
117     print "locale.getlocale():", locale.getlocale()
118     print "_defaultLanguage, _defaultEncoding:", _defaultLanguage, _defaultEncoding
119     stringsToTranslate = ("&File", "&Edit", "&Help", "Application finished.")
120     max_len = {}
121     for s in stringsToTranslate:
122         max_len[s] = len(s)
123     translatedStrings = []
124     for lang in sorted(set(_languageAliases.values()) - set(("en",))):
125         translatedStringsLine = [lang]
126         setLanguage(lang)
127         for s in stringsToTranslate:
128             translated = _(s)
129             translatedStringsLine.append(translated)
130             max_len[s] = max(max_len[s], len(translated))
131         translatedStrings.append(tuple(translatedStringsLine))
132
133     def line(strings=None):
134         if strings is None:
135             # print the boundary
136             lin =  "+----"
137             for s in stringsToTranslate:
138                 lin += "+-%s-" % ("-" * max_len[s])
139             lin += "+"
140         else:
141             # print the text
142             lin = ''
143             for idx, s in enumerate(strings):
144                 if idx == 0:
145                     len_s = 2
146                 else:
147                     len_s = max_len.get(stringsToTranslate[idx-1], len(s))
148                 s = s.decode("utf-8")
149                 lin += "| %s " % s.ljust(len_s)
150             lin += "|"
151         return lin
152
153     print line()
154     print line(("en",) + stringsToTranslate)
155     print line()
156     for l in translatedStrings:
157         setLanguage(l[0])
158         print line(l)
159     print line()
160    
Note: See TracBrowser for help on using the browser.