def UpdateHtml(): strBaseDir = os.path.join(os.getcwd(), 'website','app') for strFile in ['noaccess.html', 'noaccess_guest.html', 'noaccess_registered.html']: for dLocaleInfo in LocaleInfo.LocaleListSortedByName(): astrLocaleLinks = [] for dLocaleInfo2 in LocaleInfo.LocaleListSortedByName(): strClass = '' if dLocaleInfo2['locale'] == dLocaleInfo['locale']: strClass = 'selected' astrLocaleLinks.append('\t<a href="/?locale=' + dLocaleInfo2['locale'] + '" class="' + strClass + '">' + dLocaleInfo2['name'] + '</a>') strFooterLocaleLinks = "\n\t\t|\n".join(astrLocaleLinks) strPath = os.path.join(strBaseDir, dLocaleInfo['locale'], strFile) try: fin = open(strPath, 'rb') strContents = fin.read() fin.close() except: strPath = strPath.replace(dLocaleInfo['locale'], 'en_US') print "Reading contents from en_US location: ", strPath fin = open(strPath, 'rb') strContents = fin.read() fin.close() try: strOut = ReplaceGeneratedCode2(strContents, "FooterLocaleList", strFooterLocaleLinks) except: print "Error writing", strPath print "strContents" print strContents raise P4File.p4write(strPath, strOut, "updateLocales")
def __init__(self, datadir="/usr/share/language-selector/", globalConfDir="/etc/fonts"): self.datadir="%s/fontconfig" % datadir self._datadir = datadir self.globalConfDir=globalConfDir self.li = LocaleInfo("languagelist", datadir)
def AddNewLocales(): # create client/loc/<locale> dirs as needed for dLocaleInfo in LocaleInfo.LocaleListSortedByName(): strClientLocPath = os.path.join('client', 'loc', dLocaleInfo['locale']) if not os.path.exists(strClientLocPath): # Make the client/loc/<locale> directory print "Createing locale directory: " + strClientLocPath os.mkdir(strClientLocPath) strFrameworkPath = os.path.join('flex3_2sdk', 'frameworks', 'locale', dLocaleInfo['locale']) if not os.path.exists(strFrameworkPath): p4c = GetP4C('dummyloc') print "Creating dummy localized framework bundles" CopyFrameworkLocales(dLocaleInfo['locale']) p4c.Add(strFrameworkPath)
pkgname.endswith('-' + li.languageCode): self[pkgname].mark_delete() else: for pkgname in pkgs: self[pkgname].mark_install() except SystemError: raise ExceptionPkgCacheBroken() def getLanguageInformation(self): """ returns a list with language packs/support packages """ res = [] for (code, lang) in self._localeinfo._lang.items(): if code == 'zh': continue li = LanguageInformation(self, code, lang) if [s for s in li.languagePkgList.values() if s.available]: res.append(li) return res if __name__ == "__main__": from LocaleInfo import LocaleInfo datadir = "/usr/share/language-selector" li = LocaleInfo("languagelist", datadir) lc = LanguageSelectorPkgCache(li, apt.progress.OpProgress()) print("available language information") print(", ".join(["%s" % x for x in lc.getLanguageInformation()]))
class FontConfigHack(object): """ abstract the fontconfig hack """ def __init__(self, datadir="/usr/share/language-selector/", globalConfDir="/etc/fonts"): self.datadir="%s/fontconfig" % datadir self._datadir = datadir self.globalConfDir=globalConfDir self.li = LocaleInfo("languagelist", datadir) def _getLocaleCountryFromFileName(self, name): """ internal helper to extracr from our fontconfig filenames of the form 69-language-selector-zh-tw.conf the locale and country returns string of the form locale_COUTNRY (e.g. zh_TW) """ fname = os.path.splitext(os.path.basename(name))[0] (head, ll, cc) = string.rsplit(fname, "-", 2) return "%s_%s" % (ll, cc.upper()) def getAvailableConfigs(self): """ get the configurations we have as a list of languages (returns a list of ['zh_CN','zh_TW']) """ res = [] pattern = "%s/conf.avail/69-language-selector-*" % self.globalConfDir for name in glob.glob(pattern): res.append(self._getLocaleCountryFromFileName(name)) return res def getCurrentConfig(self): """ returns the current language configuration as a string (e.g. zh_CN) if the configfile is not a symlink it raises a ExceptionNotSymlink exception if the file dosn't exists raise a ExceptionUnconfigured exception """ pattern = "%s/conf.d/69-language-selector-*" % self.globalConfDir current_config = glob.glob(pattern) if len(current_config) == 0: raise ExceptionUnconfigured() if len(current_config) > 1: raise ExceptionMultipleConfigurations() return self._getLocaleCountryFromFileName(current_config[0]) def removeConfig(self): """ removes the current fontconfig-voodoo configuration and do some sanity checking """ pattern = "%s/conf.d/*-language-selector-*" % self.globalConfDir for f in glob.glob(pattern): if os.path.exists(f): os.unlink(f) def setConfig(self, locale): """ set the configuration for 'locale'. if locale can't be found a NoConfigurationForLocale exception it thrown """ macr = macros.LangpackMacros(self._datadir, locale) locale = macr["LOCALE"] # check if we have a config if locale not in self.getAvailableConfigs(): raise ExceptionNoConfigForLocale() # remove old symlink self.removeConfig() # do the symlinks, link from /etc/fonts/conf.avail in /etc/fonts/conf.d basedir = "%s/conf.avail/" % self.globalConfDir for pattern in ["*-language-selector-%s-%s.conf" % (macr["LCODE"], macr["CCODE"].lower()), "*-language-selector-%s.conf" % macr["LCODE"], ]: for f in glob.glob(os.path.join(basedir,pattern)): fname = os.path.basename(f) from_link = os.path.join(self.globalConfDir,"conf.avail",fname) to_link = os.path.join(self.globalConfDir, "conf.d", fname) os.symlink(from_link, to_link) return True def setConfigBasedOnLocale(self): """ set the configuration based on the locale in LocaleInfo. If no configuration is found the fontconfig config is set to 'none' Can throw a exception """ lang = self.li.getUserDefaultLanguage()[1] if len(lang) == 0: lang = self.li.getSystemDefaultLanguage()[1] locale = language2locale(lang) self.setConfig(locale)
def __init__(self, datadir=""): self._datadir = datadir # load the localeinfo "database" self._localeinfo = LocaleInfo("languagelist", self._datadir) self._cache = None
class LanguageSelectorBase(object): """ base class for language-selector code """ def __init__(self, datadir=""): self._datadir = datadir # load the localeinfo "database" self._localeinfo = LocaleInfo("languagelist", self._datadir) self._cache = None def openCache(self, progress): self._cache = LangCache.LanguageSelectorPkgCache(self._localeinfo, progress) def getMissingLangPacks(self): """ return a list of language packs that are not installed but should be installed """ if self._datadir: ls = language_support_pkgs.LanguageSupport(self._cache, os.path.join(self._datadir, "data", "pkg_depends")) else: ls = language_support_pkgs.LanguageSupport(self._cache) return ls.by_locale(self._localeinfo.getSystemDefaultLanguage()[0]) def writeSysFormatsSetting(self, sysFormats): """ write various LC_* variables (e.g. de_DE.UTF-8) """ bus = dbus.SystemBus() obj = bus.get_object('com.ubuntu.LanguageSelector','/') iface = dbus.Interface(obj,dbus_interface="com.ubuntu.LanguageSelector") iface.SetSystemDefaultFormatsEnv(sysFormats) def writeSysLanguageSetting(self, sysLanguage): """ write the system "LANGUAGE" and "LANG" variables """ bus = dbus.SystemBus() obj = bus.get_object('com.ubuntu.LanguageSelector','/') iface = dbus.Interface(obj,dbus_interface="com.ubuntu.LanguageSelector") iface.SetSystemDefaultLanguageEnv(sysLanguage) def writeUserFormatsSetting(self, userFormats): """ write various LC_* variables (e.g. de_DE.UTF-8) """ uid = os.getuid() if uid == 0: warnings.warn("No formats locale saved for user '%s'." % os.getenv('USER')) return bus = dbus.SystemBus() obj = bus.get_object('org.freedesktop.Accounts', '/org/freedesktop/Accounts/User%i' % uid) iface = dbus.Interface(obj, dbus_interface='org.freedesktop.Accounts.User') macr = macros.LangpackMacros(self._datadir, userFormats) iface.SetFormatsLocale(macr['SYSLOCALE']) def writeUserLanguageSetting(self, userLanguage): """ write the user "LANGUAGE" and "LANG" variables """ uid = os.getuid() if uid == 0: warnings.warn("No language saved for user '%s'." % os.getenv('USER')) return bus = dbus.SystemBus() obj = bus.get_object('org.freedesktop.Accounts', '/org/freedesktop/Accounts/User%i' % uid) iface = dbus.Interface(obj, dbus_interface='org.freedesktop.Accounts.User') iface.SetLanguage(userLanguage)
class FontConfigHack(object): """ abstract the fontconfig hack """ def __init__(self, datadir="/usr/share/language-selector/", globalConfDir="/etc/fonts"): self.datadir="%s/fontconfig" % datadir self._datadir = datadir self.globalConfDir=globalConfDir self.li = LocaleInfo("languagelist", datadir) def _getLocaleCountryFromFileName(self, name): """ internal helper to extracr from our fontconfig filenames of the form 69-language-selector-zh-tw.conf the locale and country returns string of the form locale_COUTNRY (e.g. zh_TW) """ fname = os.path.splitext(os.path.basename(name))[0] (head, ll, cc) = fname.rsplit("-", 2) return "%s_%s" % (ll, cc.upper()) def getAvailableConfigs(self): """ get the configurations we have as a list of languages (returns a list of ['zh_CN','zh_TW']) """ res = [] pattern = "%s/conf.avail/69-language-selector-*" % self.globalConfDir for name in glob.glob(pattern): res.append(self._getLocaleCountryFromFileName(name)) return res def getCurrentConfig(self): """ returns the current language configuration as a string (e.g. zh_CN) if the configfile is not a symlink it raises a ExceptionNotSymlink exception if the file dosn't exists raise a ExceptionUnconfigured exception """ pattern = "%s/conf.d/69-language-selector-*" % self.globalConfDir current_config = glob.glob(pattern) if len(current_config) == 0: raise ExceptionUnconfigured() if len(current_config) > 1: raise ExceptionMultipleConfigurations() return self._getLocaleCountryFromFileName(current_config[0]) def removeConfig(self): """ removes the current fontconfig-voodoo configuration and do some sanity checking """ pattern = "%s/conf.d/*-language-selector-*" % self.globalConfDir for f in glob.glob(pattern): if os.path.exists(f): os.unlink(f) def setConfig(self, locale): """ set the configuration for 'locale'. if locale can't be found a NoConfigurationForLocale exception it thrown """ macr = macros.LangpackMacros(self._datadir, locale) locale = macr["LOCALE"] # check if we have a config if locale not in self.getAvailableConfigs(): raise ExceptionNoConfigForLocale() # remove old symlink self.removeConfig() # do the symlinks, link from /etc/fonts/conf.avail in /etc/fonts/conf.d basedir = "%s/conf.avail/" % self.globalConfDir for pattern in ["*-language-selector-%s-%s.conf" % (macr["LCODE"], macr["CCODE"].lower()), "*-language-selector-%s.conf" % macr["LCODE"], ]: for f in glob.glob(os.path.join(basedir,pattern)): fname = os.path.basename(f) from_link = os.path.join(self.globalConfDir,"conf.avail",fname) to_link = os.path.join(self.globalConfDir, "conf.d", fname) os.symlink(from_link, to_link) return True def setConfigBasedOnLocale(self): """ set the configuration based on the locale in LocaleInfo. If no configuration is found the fontconfig config is set to 'none' Can throw a exception """ lang = self.li.getUserDefaultLanguage()[1] if len(lang) == 0: lang = self.li.getSystemDefaultLanguage()[1] locale = language2locale(lang) self.setConfig(locale)
def UpdateLocaleInfoAs(): print "Updating LocaleInfo.as" strPath = os.path.join(os.getcwd(), 'as','util','picnik','util','LocaleInfo.as') fin = open(strPath, 'rb') strContents = fin.read() fin.close() strInsert = "\t\tstatic private var _aobAllLocales:Array = [\n\t\t\t" fFirst = True for dLocaleInfo in LocaleInfo.LocaleListSortedByName(): if not fFirst: strInsert += ",\n\t\t\t" strLine = "{" fFirstKey = True # these are the keys we are interested in dKeys = { 'label':{'fnGet':lambda x : x['name']}, 'locale':{'sortPriority':0}, 'flag':{'fnGet':lambda x : x['locale'][3:].lower()}, 'useSystemFont':{}, 'nonBold':{}, 'countries':{}, 'googleCode':{}, 'googlePlus':{'fOptional':True} } atKeys = sorted(dKeys.items(), key=lambda t: (t[1].get('sortPriority', 100), t[0])) for atKeys in atKeys: strKey, dKeyInfo = atKeys if 'fnGet' in dKeyInfo: obVal = dKeyInfo['fnGet'](dLocaleInfo) else: if not (strKey in dLocaleInfo): if dKeyInfo.get('fOptional', False): continue else: print "ERROR: Locale missing field: " + strKey print dLocaleInfo sys.exit(1) obVal = dLocaleInfo[strKey] if not fFirstKey: strLine += ", " fFirstKey = False strLine += strKey + ": " if type(obVal) == type(True): strLine += str(obVal).lower() elif type(obVal) == type([]): strLine += str(obVal) else: # everything else is a string strLine += "'" + str(obVal) + "'" strLine += "}" strInsert += strLine fFirst = False strInsert += "\n\t\t];\n" strOut = ReplaceGeneratedCode(strContents, "LocaleInfo", strInsert) P4File.p4write(strPath, strOut, "updateLocales")
class LanguageSelectorBase(object): """ base class for language-selector code """ def __init__(self, datadir=""): self._datadir = datadir # load the localeinfo "database" self._localeinfo = LocaleInfo("languagelist", self._datadir) self._cache = None def openCache(self, progress): self._cache = LanguageSelectorPkgCache(self._localeinfo, progress) def getMissingLangPacks(self): """ return a list of language packs that are not installed but should be installed """ missing = [] for langInfo in self._cache.getLanguageInformation(): #print langInfo.languageCode trans_package = "language-pack-%s" % langInfo.languageCode # we have a langpack installed, see if we have all of them if (trans_package in self._cache and \ (self._cache[trans_package].is_installed or \ self._cache[trans_package].marked_install or \ self._cache[trans_package].marked_upgrade) and \ not self._cache[trans_package].marked_delete): #print "IsInstalled: %s " % trans_package #print self._cache.pkg_translations[langInfo.languageCode] if langInfo.languageCode in self._cache.pkg_translations: for (pkg, translation) in self._cache.pkg_translations[langInfo.languageCode]: if (pkg in self._cache and \ (self._cache[pkg].is_installed or \ self._cache[pkg].marked_install or \ self._cache[pkg].marked_upgrade) and \ not self._cache[pkg].marked_delete and \ translation in self._cache and \ ((not self._cache[translation].is_installed and \ not self._cache[translation].marked_install and \ not self._cache[translation].marked_upgrade) or \ self._cache[translation].marked_delete) and \ not translation in missing): missing.append(translation) # now check for a missing default language support default_lang = self._localeinfo.getSystemDefaultLanguage()[0] macr = macros.LangpackMacros(self._datadir, default_lang) default_lang = macr["LOCALE"] pkgcode = macr["PKGCODE"] # # if there is no default lang, return early # if default_lang is None: # return missing # # Fallback is English # pkgcode = 'en' # if default_lang in self._cache.langpack_locales: # pkgcode = self._cache.langpack_locales[default_lang] trans_package = "language-pack-%s" % pkgcode if (trans_package in self._cache and not self._cache[trans_package].is_installed): missing += [trans_package] if pkgcode in self._cache.pkg_translations: for (pkg, translation) in self._cache.pkg_translations[pkgcode]: if (self._cache[pkg].is_installed and not self._cache[translation].is_installed): missing.append(translation) support_packages = LanguageSelectorPkgCache._getPkgList(self._cache, pkgcode) for support_package in support_packages: if (support_package in self._cache and not self._cache[support_package].is_installed): missing.append(support_package) if pkgcode in self._cache.pkg_writing: for (pkg, pull_pkg) in self._cache.pkg_writing[pkgcode]: if '|' in pkg: # multiple dependencies, if one of them is installed, pull the pull_pkg for p in pkg.split('|'): if self._cache[p] and \ (self._cache[p].is_installed or \ self._cache[p].marked_install or \ self._cache[p].marked_upgrade) and \ not self._cache[p].marked_delete and \ pull_pkg in self._cache and \ ((not self._cache[pull_pkg].is_installed and \ not self._cache[pull_pkg].marked_install and \ not self._cache[pull_pkg].marked_upgrade) or \ self._cache[pull_pkg].marked_delete) and \ not pull_pkg in missing: missing.append(pull_pkg) else: if pkg in self._cache and \ (self._cache[pkg].is_installed or \ self._cache[pkg].marked_install or \ self._cache[pkg].marked_upgrade) and \ not self._cache[pkg].marked_delete and \ pull_pkg in self._cache and \ ((not self._cache[pull_pkg].is_installed and \ not self._cache[pull_pkg].marked_install and \ not self._cache[pull_pkg].marked_upgrade) or \ self._cache[pull_pkg].marked_delete) and \ not pull_pkg in missing: missing.append(pull_pkg) return missing def writeSysLangSetting(self, sysLang): """ write the system "LANG" variable (e.g. de_DE.UTF-8) """ bus = dbus.SystemBus() obj = bus.get_object('com.ubuntu.LanguageSelector','/') iface = dbus.Interface(obj,dbus_interface="com.ubuntu.LanguageSelector") iface.SetSystemDefaultLangEnv(sysLang) def writeSysLanguageSetting(self, sysLanguage): """ write the system "LANGUAGE" and "LC_MESSAGES" variables """ bus = dbus.SystemBus() obj = bus.get_object('com.ubuntu.LanguageSelector','/') iface = dbus.Interface(obj,dbus_interface="com.ubuntu.LanguageSelector") iface.SetSystemDefaultLanguageEnv(sysLanguage) def writeUserLangSetting(self, userLang): """ write the user "LANG" variable (e.g. de_DE.UTF-8) """ conffiles = [ os.path.expanduser("~/.profile") ] macr = macros.LangpackMacros(self._datadir, userLang) findString = "export LANG=" setString = "export LANG=\"%s\"\n" % macr["SYSLOCALE"] find_string_and_replace(findString, setString, conffiles) def writeUserLanguageSetting(self, userLanguage): """ write the user "LANGUAGE" variable (e.g. de:en_GB:en) and other language related environment variables (e.g. de_DE.UTF-8) """ uid = os.getuid() if uid == 0: warnings.warn("No language saved for user '%s'." % os.getenv('USER')) return bus = dbus.SystemBus() obj = bus.get_object('org.freedesktop.Accounts', '/org/freedesktop/Accounts/User%i' % uid) iface = dbus.Interface(obj, dbus_interface='org.freedesktop.Accounts.User') iface.SetLanguage(userLanguage)
class LanguageSelectorBase(object): """ base class for language-selector code """ def __init__(self, datadir=""): self._datadir = datadir # load the localeinfo "database" self._localeinfo = LocaleInfo("languagelist", self._datadir) self._cache = None def openCache(self, progress): self._cache = LangCache.LanguageSelectorPkgCache( self._localeinfo, progress) def getMissingLangPacks(self): """ return a list of language packs that are not installed but should be installed """ if self._datadir: ls = language_support_pkgs.LanguageSupport( self._cache, os.path.join(self._datadir, "data", "pkg_depends")) else: ls = language_support_pkgs.LanguageSupport(self._cache) return ls.by_locale(self._localeinfo.getSystemDefaultLanguage()[0]) def writeSysFormatsSetting(self, sysFormats): """ write various LC_* variables (e.g. de_DE.UTF-8) """ bus = dbus.SystemBus() obj = bus.get_object('com.ubuntu.LanguageSelector', '/') iface = dbus.Interface(obj, dbus_interface="com.ubuntu.LanguageSelector") iface.SetSystemDefaultFormatsEnv(sysFormats) def writeSysLanguageSetting(self, sysLanguage): """ write the system "LANGUAGE" and "LANG" variables """ bus = dbus.SystemBus() obj = bus.get_object('com.ubuntu.LanguageSelector', '/') iface = dbus.Interface(obj, dbus_interface="com.ubuntu.LanguageSelector") iface.SetSystemDefaultLanguageEnv(sysLanguage) def writeUserFormatsSetting(self, userFormats): """ write various LC_* variables (e.g. de_DE.UTF-8) """ uid = os.getuid() if uid == 0: warnings.warn("No formats locale saved for user '%s'." % os.getenv('USER')) return bus = dbus.SystemBus() obj = bus.get_object('org.freedesktop.Accounts', '/org/freedesktop/Accounts/User%i' % uid) iface = dbus.Interface(obj, dbus_interface='org.freedesktop.Accounts.User') macr = macros.LangpackMacros(self._datadir, userFormats) iface.SetFormatsLocale(macr['SYSLOCALE']) def writeUserLanguageSetting(self, userLanguage): """ write the user "LANGUAGE" and "LANG" variables """ uid = os.getuid() if uid == 0: warnings.warn("No language saved for user '%s'." % os.getenv('USER')) return bus = dbus.SystemBus() obj = bus.get_object('org.freedesktop.Accounts', '/org/freedesktop/Accounts/User%i' % uid) iface = dbus.Interface(obj, dbus_interface='org.freedesktop.Accounts.User') iface.SetLanguage(userLanguage)
strID = str(node.getAttribute('id')) if not strID in dLocTips: print "Adding missing tip " + strID + " to " + strLocFile fChanges = True xmlLocTips.documentElement.appendChild(node) if fChanges: strXML = xmlLocTips.toxml(encoding='utf-8') writeFile(strLocFile, strXML) # Read the list of locales in client/loc patLocale = re.compile('[a-z][a-z]_[a-z][a-z]', re.IGNORECASE) astrLocales = [] for dLocaleInfo in LocaleInfo.LocaleListSortedByName(): if dLocaleInfo['locale'] != 'en_US': astrLocales.append(dLocaleInfo['locale']) AddNewLocales() # Take care of properties strPropFileBase = 'client/loc/en_US' for strPropFileName in os.listdir(strPropFileBase): strSrcPropFilePath = os.path.join(strPropFileBase, strPropFileName) if strSrcPropFilePath.lower().endswith('.' + 'properties'): pfSrc = PropFile(strSrcPropFilePath) # Found a properties file. for strLocale in astrLocales: strDstPropFilePath = strSrcPropFilePath.replace('en_US', strLocale)