desktop_app/app/core/localizer.py
2025-09-08 19:24:27 +03:00

58 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import json
import os
from PySide6.QtCore import QSettings
from app.core import config
class Localizer:
"""Класс для загрузки и работы с переводами"""
def __init__(self):
self.settings = QSettings("yobble_messenger", "Localization")
self.locales_path = os.path.join("app/locales")
self.translations = {}
self.lang = self.settings.value("language", "ru")
available_langs = self.get_available_languages()
if self.lang not in available_langs:
self.lang = available_langs[0] if available_langs else "ru"
self.load_language(self.lang)
def get_available_languages(self):
"""Возвращает список доступных языков по файлам в папке locales"""
langs = []
if os.path.exists(self.locales_path):
for file in os.listdir(self.locales_path):
if file.endswith(".json"):
langs.append(os.path.splitext(file)[0])
return langs
def load_language(self, lang):
"""Загружает перевод из JSON-файла"""
lang_file = os.path.join(self.locales_path, f"{lang}.json")
if os.path.exists(lang_file):
with open(lang_file, "r", encoding="utf-8") as file:
self.translations = json.load(file)
self.lang = lang
self.settings.setValue("language", lang)
if config.DEBUG: print(f"[Localizer.load_language] ✅ Язык загружен: {lang}")
else:
if config.DEBUG: print(f"[Localizer.load_language] ❌ Файл локализации не найден: {lang_file}")
def translate(self, key, code=None):
"""Возвращает перевод слова"""
text = self.translations.get(key, key)
if code is not None:
text = f"{text} {code}"
return text
def switch_language(self, lang):
"""Переключает языки, если язык доступен"""
if lang in self.get_available_languages():
self.load_language(lang)
else:
if config.DEBUG: print(f"[Localizer.switch_language] ❌ Язык не найден: {lang}")
# Глобальный экземпляр
localizer = Localizer()