diff --git a/.gitignore b/.gitignore index 2983b48..f6dd14a 100644 --- a/.gitignore +++ b/.gitignore @@ -108,7 +108,6 @@ dist/ downloads/ eggs/ .eggs/ -lib/ lib64/ parts/ sdist/ diff --git a/lib/i18n/__init__.py b/lib/i18n/__init__.py new file mode 100644 index 0000000..0531682 --- /dev/null +++ b/lib/i18n/__init__.py @@ -0,0 +1,11 @@ +"""Public package interface for the reusable i18n library. + +The library ships with an empty ``__init__.py``. This project relies on the +documented ``from i18n import I18n`` / ``from i18n import i18n`` usage shown +in the library's own README, so the class (and, once constructed, the +singleton instance) are re-exported here. +""" + +from .i18n import I18n + +__all__ = ["I18n"] diff --git a/lib/i18n/i18n.py b/lib/i18n/i18n.py new file mode 100644 index 0000000..0aadd37 --- /dev/null +++ b/lib/i18n/i18n.py @@ -0,0 +1,216 @@ +"""Reusable internationalization support with a process-wide singleton.""" + +from __future__ import annotations + +import json +import sys +from collections.abc import Callable +from pathlib import Path +from typing import Any + + +class I18n: + """Singleton internationalization manager. + + The first construction initializes the singleton. Later constructions + return the same instance and do not reinitialize it. + """ + + _instance: I18n | None = None + + def __new__( + cls, + default_language: str = "en", + available_languages: dict[str, str] | None = None, + project_root: str | Path | None = None, + ) -> I18n: + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + def __init__( + self, + default_language: str = "en", + available_languages: dict[str, str] | None = None, + project_root: str | Path | None = None, + ) -> None: + if getattr(self, "_initialized", False): + return + + self.default_language = default_language + self.available_languages = dict( + available_languages if available_languages is not None + else {"en": "English"} + ) + + if self.default_language not in self.available_languages: + raise ValueError( + f"Default language {self.default_language!r} is not " + "listed in available_languages" + ) + + self.project_root = ( + Path(project_root).resolve() + if project_root is not None + else self._find_project_root() + ) + self.i18n_root = self.project_root / "i18n" + + self._listeners: list[Callable[[str], None]] = [] + self._current_language = self.default_language + + # Loading the default language is part of construction and therefore + # fails immediately if its resource is missing or invalid. + self._translations = self._load_strings(self.default_language) + self._english_translations: dict[str, str] | None = None + if self.default_language == "en": + self._english_translations = self._translations + + self._initialized = True + + @staticmethod + def _find_project_root() -> Path: + """Return the directory containing the executed program.""" + executable = Path(sys.argv[0]) + if not executable.is_absolute(): + executable = Path.cwd() / executable + return executable.resolve().parent + + def _language_dir(self, code: str) -> Path: + return self.i18n_root / code + + def _load_strings(self, code: str) -> dict[str, str]: + path = self._language_dir(code) / "strings.json" + if not path.is_file(): + raise FileNotFoundError( + f"Translation file not found for language {code!r}: {path}" + ) + + try: + with path.open("r", encoding="utf-8") as fh: + data: Any = json.load(fh) + except json.JSONDecodeError as exc: + raise ValueError(f"Invalid JSON in translation file: {path}") from exc + + if not isinstance(data, dict): + raise ValueError( + f"Translation file must contain a JSON object: {path}" + ) + if not all( + isinstance(key, str) and isinstance(value, str) + for key, value in data.items() + ): + raise ValueError( + f"Translation keys and values must both be strings: {path}" + ) + + return data + + def _get_english_translations(self) -> dict[str, str]: + if self._english_translations is None: + self._english_translations = self._load_strings("en") + return self._english_translations + + def get_language(self) -> str: + """Return the current language shortcut.""" + return self._current_language + + def set_language(self, code: str) -> None: + """Load, activate and announce a new language.""" + if code not in self.available_languages: + raise ValueError(f"Unknown language: {code!r}") + if code == self._current_language: + return + + # Do all I/O before changing state or notifying listeners. + translations = self._load_strings(code) + self._translations = translations + self._current_language = code + + for listener in list(self._listeners): + listener(code) + + def get_default_language(self) -> str: + """Return the default language shortcut.""" + return self.default_language + + def get_available_languages(self) -> dict[str, str]: + """Return the available languages.""" + return self.available_languages + + def _get_translations(self) -> dict[str, str]: + """Return the current language dictionary.""" + return self._translations + + def add_language_change_listener( + self, callback: Callable[[str], None] + ) -> None: + """Register a callback receiving the new language code.""" + if callback not in self._listeners: + self._listeners.append(callback) + + def remove_language_change_listener( + self, callback: Callable[[str], None] + ) -> None: + """Remove a previously registered callback.""" + if callback in self._listeners: + self._listeners.remove(callback) + + # Compatibility aliases. + add_listener = add_language_change_listener + remove_listener = remove_language_change_listener + + def t(self, key: str, /, default: str | None = None, **kwargs: Any) -> str: + """Translate a key with current-language/English/default/key fallback.""" + text = self._translations.get(key) + if text is None: + text = self._get_english_translations().get(key) + if text is None: + text = default if default is not None else key + + if kwargs: + try: + text = text.format(**kwargs) + except (KeyError, IndexError): + pass + return text + + def prop_label(self, type_name: str, spec: Any) -> str: + """Return the translated label for an existing PropertySpec.""" + override_key = f"prop.{type_name}.{spec.name}" + override = self._translations.get(override_key) + if override is None: + override = self._get_english_translations().get(override_key) + if override is not None: + return override + + return self.t(f"prop.{spec.name}", default=spec.label) + + def get_help(self) -> str: + """Return help.md for the current language, falling back to English.""" + path = self._language_dir(self._current_language) / "help.md" + if not path.is_file() and self._current_language != "en": + path = self._language_dir("en") / "help.md" + + if not path.is_file(): + raise FileNotFoundError( + f"Help file not found for language {self._current_language!r}: {path}" + ) + return path.read_text(encoding="utf-8") + +# Deactivated the i18n var because it triggers the constructor with the default +# language, which is en here. This triggering is done while importing the i18n class. +# Due to being a singleton a second call to the constructor does nothing but returning +# the already instantiated object with the default set to "en" +# +# DEFAULT_LANGUAGE = "en" +# AVAILABLE_LANGUAGES = { +# "de": "Deutsch", +# "en": "English", +# } + +# The application's reusable singleton. +# i18n = I18n( +# default_language=DEFAULT_LANGUAGE, +# available_languages=AVAILABLE_LANGUAGES, +# )