i18n: Fix internationalization problems

This commit is contained in:
Valentin Lorentz 2010-11-11 12:01:56 +01:00
parent 02cb15d522
commit 323ffe1a1f
3 changed files with 43 additions and 32 deletions

View File

@ -61,6 +61,7 @@ import textwrap
started = time.time() started = time.time()
import supybot import supybot
import supybot.i18n as i18n
import supybot.utils as utils import supybot.utils as utils
import supybot.registry as registry import supybot.registry as registry
import supybot.questions as questions import supybot.questions as questions
@ -178,6 +179,7 @@ if __name__ == '__main__':
docs/GETTING_STARTED and follow the instructions.""")) docs/GETTING_STARTED and follow the instructions."""))
else: else:
registryFilename = args.pop() registryFilename = args.pop()
i18n.getLocaleFromRegistryFilename(registryFilename)
try: try:
# The registry *MUST* be opened before importing log or conf. # The registry *MUST* be opened before importing log or conf.
registry.open(registryFilename) registry.open(registryFilename)
@ -210,6 +212,7 @@ if __name__ == '__main__':
sys.exit(-1) sys.exit(-1)
import supybot.conf as conf import supybot.conf as conf
import supybot.world as world import supybot.world as world
i18n.import_conf()
world.starting = True world.starting = True
def closeRegistry(): def closeRegistry():

View File

@ -37,6 +37,7 @@ import re
import sys import sys
import time import time
import threading import threading
conf = None
# Don't import conf here ; because conf needs this module # Don't import conf here ; because conf needs this module
WAITING_FOR_MSGID = 1 WAITING_FOR_MSGID = 1
@ -47,16 +48,26 @@ IN_MSGSTR = 4
MSGID = 'msgid "' MSGID = 'msgid "'
MSGSTR = 'msgstr "' MSGSTR = 'msgstr "'
currentLocale = 'en'
def getLocaleFromRegistryFilename(filename):
"""Called by the 'supybot' script. Gets the locale name before conf is
loaded."""
global currentLocale
for line in open(filename, 'r'):
if line.startswith('supybot.language: '):
currentLocale = line[len('supybot.language: '):]
def import_conf(): def import_conf():
import supybot.conf as conf """Imports the conf into this module"""
globals().update({'conf': conf}) global conf
conf = __import__('supybot.conf').conf
conf.registerGlobalValue(conf.supybot, 'language', conf.registerGlobalValue(conf.supybot, 'language',
conf.registry.String('en', """Determines the bot's default language. conf.registry.String(currentLocale, """Determines the bot's default
Valid values are things like en, fr, de, etc.""")) language. Valid values are things like en, fr, de, etc."""))
for key in i18nClasses:
i18nClasses[key].loadLocale()
def getPluginDir(plugin_name): def getPluginDir(plugin_name):
"""Gets the directory of the given plugin"""
filename = None filename = None
try: try:
filename = sys.modules[plugin_name].__file__ filename = sys.modules[plugin_name].__file__
@ -74,6 +85,8 @@ def getPluginDir(plugin_name):
return return
def getLocalePath(name, localeName, extension): def getLocalePath(name, localeName, extension):
"""Gets the path of the locale file of the given plugin ('supybot' stands
for the core)."""
if name != 'supybot': if name != 'supybot':
directory = getPluginDir(name) + 'locale' directory = getPluginDir(name) + 'locale'
else: else:
@ -85,7 +98,15 @@ i18nClasses = {}
internationalizedCommands = {} internationalizedCommands = {}
internationalizedFunctions = [] # No need to know there name internationalizedFunctions = [] # No need to know there name
def reloadLocals(): def reloadLocalesIfRequired():
global currentLocale
if conf is None:
return
if currentLocale != conf.supybot.language():
currentLocale = conf.supybot.language()
reloadLocales()
def reloadLocales():
for pluginName in i18nClasses: for pluginName in i18nClasses:
i18nClasses[pluginName].loadLocale() i18nClasses[pluginName].loadLocale()
for commandHash in internationalizedCommands: for commandHash in internationalizedCommands:
@ -111,17 +132,12 @@ class _PluginInternationalization:
self.name = name self.name = name
self.currentLocaleName = None self.currentLocaleName = None
i18nClasses.update({name: self}) i18nClasses.update({name: self})
if name != 'supybot' and not 'conf' in globals():
# if conf is loadable but not loaded
import_conf()
self.loadLocale() self.loadLocale()
def loadLocale(self, localeName=None): def loadLocale(self, localeName=None):
"""(Re)loads the locale used by this class.""" """(Re)loads the locale used by this class."""
if localeName is None and 'conf' in globals(): if localeName is None:
localeName = conf.supybot.language() localeName = currentLocale
elif localeName is None:
localeName = 'en'
self.currentLocaleName = localeName self.currentLocaleName = localeName
self._loadL10nCode() self._loadL10nCode()
@ -184,14 +200,16 @@ class _PluginInternationalization:
self._addToDatabase(untranslated, translated) self._addToDatabase(untranslated, translated)
def _addToDatabase(self, untranslated, translated): def _addToDatabase(self, untranslated, translated):
untranslated = self._unescape(untranslated) untranslated = self._unescape(untranslated, True)
translated = self._unescape(translated) translated = self._unescape(translated)
self.translations.update({untranslated: translated}) self.translations.update({untranslated: translated})
def _unescape(self, string): def _unescape(self, string, removeNewline=False):
import supybot.utils as utils import supybot.utils as utils
string = str.replace(string, '\\n', '\n') # gettext escapes the \n string = str.replace(string, '\\n', '\n') # gettext escapes the \n
string = utils.str.normalizeWhitespace(string, removeNewline=False) string = str.replace(string, '\\"', '"')
string = str.replace(string, "\'", "'")
string = utils.str.normalizeWhitespace(string, removeNewline)
return string return string
def __call__(self, untranslated): def __call__(self, untranslated):
@ -200,12 +218,8 @@ class _PluginInternationalization:
his is the function which is called when a plugin runs _()""" his is the function which is called when a plugin runs _()"""
if untranslated.__class__ == internationalizedString: if untranslated.__class__ == internationalizedString:
return untranslated._original return untranslated._original
untranslated = self._unescape(untranslated) untranslated = self._unescape(untranslated, True)
if not 'conf' in globals(): reloadLocalesIfRequired()
return untranslated
if self.currentLocaleName != conf.supybot.language():
# If the locale has been changed
reloadLocals()
try: try:
string = self._translate(untranslated) string = self._translate(untranslated)
return self._addTracker(string, untranslated) return self._addTracker(string, untranslated)

View File

@ -61,16 +61,10 @@ def rsplit(s, sep=None, maxsplit=-1):
def normalizeWhitespace(s, removeNewline=True): def normalizeWhitespace(s, removeNewline=True):
"""Normalizes the whitespace in a string; \s+ becomes one space.""" """Normalizes the whitespace in a string; \s+ becomes one space."""
beginning = s.startswith(' ')
ending = s.endswith(' ')
if removeNewline: if removeNewline:
s = ' '.join(s.split()) s = str.replace(s, '\n', '')
else: while ' ' in s:
s = ' '.join(s.split(' ')) s = str.replace(s, ' ', ' ')
if beginning:
s = ' ' + s
if ending:
s = s + ' '
return s return s
def distance(s, t): def distance(s, t):