Clean the translation module

This commit is contained in:
Yohann D'ANELLO
2020-11-28 01:59:52 +01:00
parent 138b2c6d54
commit 7d02604407
4 changed files with 40 additions and 24 deletions

View File

@@ -1,28 +1,44 @@
# Copyright (C) 2020 by ÿnérant, eichhornchen, nicomarg, charlse
# SPDX-License-Identifier: GPL-3.0-or-later
import gettext
import gettext as gt
from typing import Any, List
SUPPORTED_LOCALES = ["en", "fr"]
DEFAULT_LOCALE = "en"
class Translator:
"""
This module uses gettext to translate strings.
Translator.setlocale defines the language of the strings,
then gettext() translates the message.
"""
SUPPORTED_LOCALES: List[str] = ["en", "fr"]
locale: str = "en"
translators: dict = {}
_current_locale = DEFAULT_LOCALE
for language in SUPPORTED_LOCALES:
translators[language] = gt.translation(
"squirrelbattle",
localedir="locale",
languages=[language],
)
_TRANSLATORS = dict()
for language in SUPPORTED_LOCALES:
_TRANSLATORS[language] = gettext.translation("squirrelbattle",
localedir="locale",
languages=[language])
@classmethod
def setlocale(cls, lang: str) -> None:
"""
Define the language used to translate the game.
The language must be supported, otherwise nothing is done.
"""
lang = lang[:2]
if lang in cls.SUPPORTED_LOCALES:
cls.locale = lang
@classmethod
def get_translator(cls) -> Any:
return cls.translators.get(cls.locale)
def gettext(message: str) -> str:
return _TRANSLATORS.get(_current_locale,
_TRANSLATORS.get("en")).gettext(message)
def setlocale(lang: str) -> None:
global _current_locale
lang = lang[:2]
if lang in SUPPORTED_LOCALES:
_current_locale = lang
"""
Translate a message.
"""
return Translator.get_translator().gettext(message)