Translation Updates.

- Added addon_preferences so we can save users preferences into a json file.
- Made translation slightly simpler

This mostly works just have to figure out why we can't update description on reload (There only update on blender restart).
This commit is contained in:
Yusarina
2024-07-08 09:13:52 +01:00
parent 03a24650f1
commit eaafd3bb69
7 changed files with 115 additions and 58 deletions
+42 -39
View File
@@ -2,20 +2,24 @@ import os
import json
import bpy
from bpy.app.translations import locale
from ..core.register import register_wrap
from typing import Dict, List, Tuple
from ..core.addon_preferences import save_preference, get_preference
main_dir: str = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
resources_dir: str = os.path.join(main_dir, "resources")
translations_dir: str = os.path.join(resources_dir, "translations")
# Use __file__ to get the current file's directory
current_dir = os.path.dirname(os.path.abspath(__file__))
main_dir = os.path.dirname(current_dir)
resources_dir = os.path.join(main_dir, "resources")
translations_dir = os.path.join(resources_dir, "translations")
dictionary: Dict[str, str] = dict()
languages: List[str] = []
verbose: bool = True
def load_translations() -> None:
def load_translations() -> bool:
global dictionary, languages
old_dictionary = dictionary.copy()
dictionary = dict()
languages = ["auto"]
@@ -25,68 +29,67 @@ def load_translations() -> None:
if lang != "auto":
languages.append(lang)
# Check if the context and scene are available
if hasattr(bpy.context, "scene"):
# Check if the property exists before trying to access it
if hasattr(bpy.context.scene, "avatar_toolkit_language"):
language_index = bpy.context.scene.avatar_toolkit_language
if isinstance(language_index, str):
language_index = int(language_index)
if language_index == 0: # "auto"
language = bpy.context.preferences.view.language
else:
language = languages[language_index]
else:
language = bpy.context.preferences.view.language
language_index = get_preference("language", 0)
print(f"Loading translations for language index: {language_index}") # Debug print
if language_index == 0: # "auto"
language = bpy.context.preferences.view.language
else:
# Set a default language if the context or scene is not available
language = "en_US"
try:
language = languages[language_index]
except IndexError:
language = bpy.context.preferences.view.language
print(f"Selected language: {language}") # Debug print
translation_file: str = os.path.join(translations_dir, language + ".json")
if os.path.exists(translation_file):
with open(translation_file, 'r', encoding='utf-8') as file:
dictionary = json.load(file)["messages"]
print(f"Loaded translations: {dictionary}") # Debug print
else:
custom_language: str = language.split("_")[0]
custom_translation_file: str = os.path.join(translations_dir, custom_language + ".json")
if os.path.exists(custom_translation_file):
with open(custom_translation_file, 'r', encoding='utf-8') as file:
dictionary = json.load(file)["messages"]
print(f"Loaded custom translations: {dictionary}") # Debug print
else:
print(f"Translation file not found for language: {language}")
default_file: str = os.path.join(translations_dir, "en_US.json")
if os.path.exists(default_file):
with open(default_file, 'r', encoding='utf-8') as file:
dictionary = json.load(file)["messages"]
print(f"Loaded default translations: {dictionary}") # Debug print
else:
print("Default translation file 'en_US.json' not found.")
def t(phrase: str, *args, **kwargs) -> str:
return dictionary != old_dictionary
def t(phrase: str, default: str = None) -> str:
output: str = dictionary.get(phrase)
if output is None:
if verbose:
print('Warning: Unknown phrase: ' + phrase)
return phrase
return output.format(*args, **kwargs)
print(f'Warning: Unknown phrase: {phrase}')
return default if default is not None else phrase
print(f"Translating '{phrase}' to '{output}'") # Debug print
return output
def get_language_display_name(lang: str) -> str:
if lang == "auto":
return t("Language.auto", "Automatic")
return t(f"Language.{lang}", lang)
def get_languages_list(self, context) -> List[Tuple[str, str, str]]:
return [(str(i), lang, f"Use {lang} language") for i, lang in enumerate(languages)]
return [(str(i), get_language_display_name(lang), f"Use {lang} language") for i, lang in enumerate(languages)]
def refresh_translations():
def update_language(self, context):
print(f"Updating language to: {self.avatar_toolkit_language}") # Debug print
save_preference("language", int(self.avatar_toolkit_language))
load_translations()
# Force a full UI update
for window in bpy.context.window_manager.windows:
for area in window.screen.areas:
area.tag_redraw()
def update_ui(self, context):
refresh_translations()
# Force Blender to redraw all UI elements
for screen in bpy.data.screens:
for area in screen.areas:
area.tag_redraw()
# Update the Scene to trigger a full UI refresh
bpy.context.scene.update_tag()
# Reload the addon
bpy.ops.script.reload()
# Initial load of translations
print("Performing initial load of translations") # Debug print
load_translations()