/usr/share/pyshared/LanguageSelector/LocaleInfo.py is in language-selector-common 0.79.4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | # LoclaeInfo.py (c) 2006 Canonical, released under the GPL
#
# a helper class to get locale info
import re
import subprocess
import gettext
import os
import pwd
import sys
import dbus
import warnings
import macros
from gettext import gettext as _
from xml.etree.ElementTree import ElementTree
class LocaleInfo(object):
" class with handy functions to parse the locale information "
environments = ["/etc/default/locale", "/etc/environment"]
def __init__(self, languagelist_file, datadir):
self._datadir = datadir
LANGUAGELIST = os.path.join(datadir, 'data', languagelist_file)
# map language to human readable name, e.g.:
# "pt"->"Portuguise", "de"->"German", "en"->"English"
self._lang = {}
# map country to human readable name, e.g.:
# "BR"->"Brasil", "DE"->"Germany", "US"->"United States"
self._country = {}
# map locale (language+country) to the LANGUAGE environment, e.g.:
# "pt_PT"->"pt_PT:pt:pt_BR:en_GB:en"
self._languagelist = {}
# read lang file
et = ElementTree(file="/usr/share/xml/iso-codes/iso_639.xml")
it = et.getiterator('iso_639_entry')
for elm in it:
lang = elm.attrib["name"]
if "iso_639_1_code" in elm.attrib:
code = elm.attrib["iso_639_1_code"]
else:
code = elm.attrib["iso_639_2T_code"]
if not code in self._lang:
self._lang[code] = lang
# Hack for Chinese langpack split
# Translators: please translate 'Chinese (simplified)' and 'Chinese (traditional)' so that they appear next to each other when sorted alphabetically.
self._lang['zh-hans'] = _("Chinese (simplified)")
# Translators: please translate 'Chinese (simplified)' and 'Chinese (traditional)' so that they appear next to each other when sorted alphabetically.
self._lang['zh-hant'] = _("Chinese (traditional)")
# end hack
et = ElementTree(file="/usr/share/xml/iso-codes/iso_639_3.xml")
it = et.getiterator('iso_639_3_entry')
for elm in it:
lang = elm.attrib["name"]
code = elm.attrib["id"]
if not code in self._lang:
self._lang[code] = lang
# read countries
et = ElementTree(file="/usr/share/xml/iso-codes/iso_3166.xml")
it = et.getiterator('iso_3166_entry')
for elm in it:
if "common_name" in elm.attrib:
descr = elm.attrib["common_name"]
else:
descr = elm.attrib["name"]
if "alpha_2_code" in elm.attrib:
code = elm.attrib["alpha_2_code"]
else:
code = elm.attrib["alpha_3_code"]
self._country[code] = descr
# read the languagelist
for line in open(LANGUAGELIST):
tmp = line.strip()
if tmp.startswith("#") or tmp == "":
continue
w = tmp.split(";")
# FIXME: the latest localechoosers "languagelist" does
# no longer have this field for most languages, so
# deal with it and don't set LANGUAGE then
# - the interessting question is what to do
# if LANGUAGE is already set and the new
localeenv = w[6].split(":")
#print localeenv
self._languagelist[localeenv[0]] = '%s' % w[6]
def lang(self, code):
""" map language code to language name """
if code in self._lang:
return self._lang[code]
return ""
def country(self, code):
""" map country code to country name"""
if code in self._country:
return self._country[code]
return ""
def generated_locales(self):
""" return a list of locales available on the system
(running locale -a) """
locales = []
p = subprocess.Popen(["locale", "-a"], stdout=subprocess.PIPE)
for line in p.communicate()[0].split("\n"):
tmp = line.strip()
if tmp.find('.utf8') < 0:
continue
# we are only interessted in the locale, not the codec
macr = macros.LangpackMacros(self._datadir, tmp)
locale = macr["LOCALE"]
if not locale in locales:
locales.append(locale)
#print locales
return locales
def translate_language(self, lang):
"return translated language"
if lang in self._lang:
lang_name = gettext.dgettext('iso_639', self._lang[lang])
if lang_name == self._lang[lang]:
lang_name = gettext.dgettext('iso_639_3', self._lang[lang])
return lang_name
else:
return lang
def translate_country(self, country):
"""
return translated language and country of the given
locale into the given locale, e.g.
(Deutsch, Deutschland) for de_DE
"""
# macr = macros.LangpackMacros(self._datadir, locale)
# #(lang, country) = locale.split("_")
# country = macr['CCODE']
# current_language = None
# if "LANGUAGE" in os.environ:
# current_language = os.environ["LANGUAGE"]
# os.environ["LANGUAGE"]=locale
# lang_name = self.translate_language(macr['LCODE'])
if country in self._country:
country_name = gettext.dgettext('iso_3166', self._country[country])
return country_name
else:
return country
# if current_language:
# os.environ["LANGUAGE"] = current_language
# else:
# del os.environ["LANGUAGE"]
# return (lang_name, country_name)
def translate(self, locale, native=False, allCountries=False):
""" get a locale code and output a human readable name """
returnVal = ''
macr = macros.LangpackMacros(self._datadir, locale)
if native == True:
current_language = None
if "LANGUAGE" in os.environ:
current_language = os.environ["LANGUAGE"]
os.environ["LANGUAGE"] = macr["LOCALE"]
lang_name = self.translate_language(macr["LCODE"])
returnVal = lang_name
if len(macr["CCODE"]) > 0:
country_name = self.translate_country(macr["CCODE"])
# get all locales for this language
l = filter(lambda k: k.startswith(macr['LCODE']), self.generated_locales())
# only show region/country if we have more than one
if (allCountries == False and len(l) > 1) or allCountries == True:
mycountry = self.country(macr['CCODE'])
if mycountry:
returnVal = "%s (%s)" % (lang_name, country_name)
if len(macr["VARIANT"]) > 0:
returnVal = "%s - %s" % (returnVal, macr["VARIANT"].encode('UTF-8'))
if native == True:
if current_language:
os.environ["LANGUAGE"] = current_language
else:
del os.environ["LANGUAGE"]
return returnVal
# if "_" in locale:
# #(lang, country) = locale.split("_")
# (lang_name, country_name) = self.translate_locale(locale)
# # get all locales for this language
# l = filter(lambda k: k.startswith(macr['LCODE']), self.generated_locales())
# # only show region/country if we have more than one
# if len(l) > 1:
# mycountry = self.country(macr['CCODE'])
# if mycountry:
# return "%s (%s)" % (lang_name, country_name)
# else:
# return lang_name
# else:
# return lang_name
# return self.translate_language(locale)
def makeEnvString(self, code):
""" input is a language code, output a string that can be put in
the LANGUAGE enviroment variable.
E.g: en_DK -> en_DK:en
"""
if not code:
return ''
macr = macros.LangpackMacros(self._datadir, code)
langcode = macr['LCODE']
locale = macr['LOCALE']
# first check if we got somethign from languagelist
if locale in self._languagelist:
langlist = self._languagelist[locale]
# if not, fall back to "dumb" behaviour
elif locale == langcode:
langlist = locale
else:
langlist = "%s:%s" % (locale, langcode)
if not (langlist.endswith(':en') or langlist == 'en'):
langlist = "%s:en" % langlist
return langlist
def getUserDefaultLanguage(self):
formats = ''
language = ''
result = []
fname = os.path.expanduser("~/.pam_environment")
if os.path.exists(fname) and \
os.access(fname, os.R_OK):
for line in open(fname):
match_language = re.match(r'LANGUAGE=(.*)$',line)
if match_language:
language = match_language.group(1)
if 'fontconfig-voodoo' in sys.argv[0] and os.getenv('SUDO_USER'):
# handle 'sudo fontconfig-voodoo --auto' correctly
user_name = os.environ['SUDO_USER']
else:
user_name = pwd.getpwuid(os.geteuid()).pw_name
try:
bus = dbus.SystemBus()
obj = bus.get_object('org.freedesktop.Accounts', '/org/freedesktop/Accounts')
iface = dbus.Interface(obj, dbus_interface='org.freedesktop.Accounts')
user_path = iface.FindUserByName(user_name)
obj = bus.get_object('org.freedesktop.Accounts', user_path)
iface = dbus.Interface(obj, dbus_interface='org.freedesktop.DBus.Properties')
formats = iface.Get('org.freedesktop.Accounts.User', 'FormatsLocale')
if len(language) == 0:
firstLanguage = iface.Get('org.freedesktop.Accounts.User', 'Language')
language = self.makeEnvString(firstLanguage)
except Exception as msg:
# a failure here shouldn't trigger a fatal error
warnings.warn(msg.args[0].encode('UTF-8'))
pass
if len(language) == 0 and "LANGUAGE" in os.environ:
language = os.environ["LANGUAGE"]
if len(formats) == 0 and "LC_NAME" in os.environ:
formats = os.environ["LC_NAME"]
if len(formats) == 0 and "LANG" in os.environ:
formats = os.environ["LANG"]
if len(formats) > 0 and len(language) == 0:
language = self.makeEnvString(formats)
result.append(formats)
result.append(language)
return result
def getSystemDefaultLanguage(self):
lang = ''
formats = ''
language = ''
result = []
for fname in self.environments:
if os.path.exists(fname) and \
os.access(fname, os.R_OK):
for line in open(fname):
# support both LANG="foo" and LANG=foo
if line.startswith("LANG"):
line = line.replace('"','')
match_lang = re.match(r'LANG=(.*)$',line)
if match_lang:
lang = match_lang.group(1)
if line.startswith("LC_TIME"):
line = line.replace('"','')
match_formats = re.match(r'LC_TIME=(.*)$',line)
if match_formats:
formats = match_formats.group(1)
if line.startswith("LANGUAGE"):
line = line.replace('"','')
match_language = re.match(r'LANGUAGE=(.*)$',line)
if match_language:
language = match_language.group(1)
if len(lang) > 0:
break
if len(lang) == 0:
# fall back is 'en_US'
lang = 'en_US.UTF-8'
if len(language) == 0:
# LANGUAGE has not been defined, generate a string from the provided LANG value
language = self.makeEnvString(lang)
if len(formats) == 0:
formats = lang
result.append(formats)
result.append(language)
return result
def isSetSystemFormats(self):
if not os.access(self.environments[0], os.R_OK):
return False
for line in open(self.environments[0]):
if line.startswith("LC_TIME="):
return True
return False
if __name__ == "__main__":
datadir = "/usr/share/language-selector/"
li = LocaleInfo("languagelist", datadir)
print "default system locale and languages: '%s'" % li.getSystemDefaultLanguage()
print "default user locale and languages: '%s'" % li.getUserDefaultLanguage()
print li._lang
print li._country
print li._languagelist
print li.generated_locales()
|