desktop_app/app/core/localizer.py
2025-09-09 12:13:41 +03:00

79 lines
3.2 KiB
Python
Raw Permalink 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 = {}
lang_code = self.settings.value("language", "ru")
available_langs = self.get_available_languages()
available_codes = [code for code, _ in available_langs]
if lang_code not in available_codes:
lang_code = available_codes[0] if available_codes else "ru"
self.lang = lang_code
self.load_language(self.lang)
def get_available_languages(self):
"""
Возвращает список доступных языков как список кортежей:
од_языка, отображаемое_имя)
"""
langs = []
if os.path.exists(self.locales_path):
for file in os.listdir(self.locales_path):
if file.endswith(".json"):
lang_code = os.path.splitext(file)[0]
lang_file = os.path.join(self.locales_path, file)
try:
with open(lang_file, "r", encoding="utf-8") as f:
data = json.load(f)
display_name = data.get("__name__", lang_code)
langs.append((lang_code, display_name))
except Exception as e:
if config.DEBUG:
print(f"[Localizer] Ошибка чтения {file}: {e}")
langs.append((lang_code, lang_code)) # fallback
if config.DEBUG: print("langs", langs)
return langs
def load_language(self, lang_code):
"""Загружает перевод из JSON-файла"""
lang_file = os.path.join(self.locales_path, f"{lang_code}.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_code
self.settings.setValue("language", lang_code)
if config.DEBUG:
print(f"[Localizer.load_language] ✅ Язык загружен: {lang_code}")
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):
"""Переключает языки, если язык доступен"""
available_langs = [code for code, _ in self.get_available_languages()]
if lang in available_langs:
self.load_language(lang)
else:
if config.DEBUG:
print(f"[Localizer.switch_language] ❌ Язык не найден: {lang}")
# Глобальный экземпляр
localizer = Localizer()