squirrel-battle/squirrelbattle/translations.py

45 lines
1.2 KiB
Python
Raw Normal View History

2020-11-27 19:32:40 +00:00
# Copyright (C) 2020 by ÿnérant, eichhornchen, nicomarg, charlse
# SPDX-License-Identifier: GPL-3.0-or-later
2020-11-28 00:59:52 +00:00
import gettext as gt
from typing import Any, List
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 = {}
for language in SUPPORTED_LOCALES:
translators[language] = gt.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)
2020-11-27 19:32:40 +00:00
def gettext(message: str) -> str:
2020-11-28 00:59:52 +00:00
"""
Translate a message.
"""
return Translator.get_translator().gettext(message)