| 1 |
"""Localization and translation management. |
| 2 |
|
| 3 |
It handles loading language files, retrieving translated strings, and managing |
| 4 |
language-specific configurations. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import os |
| 10 |
import re |
| 11 |
|
| 12 |
from DisplayCAL.config import DATA_DIRS, DEFAULTS, STORAGE, getcfg |
| 13 |
from DisplayCAL.debughelpers import handle_error |
| 14 |
from DisplayCAL.lazydict import LazyDictYAMLUltraLite |
| 15 |
from DisplayCAL.options import DEBUG_LOCALIZATION as DEBUG |
| 16 |
from DisplayCAL.util_os import expanduseru |
| 17 |
|
| 18 |
|
| 19 |
def init(set_wx_locale: bool = False) -> None: |
| 20 |
"""Populate translation dict with found language strings and set locale. |
| 21 |
|
| 22 |
If set_wx_locale is True, set locale also for wxPython. |
| 23 |
|
| 24 |
Args: |
| 25 |
set_wx_locale (bool): Whether to set the locale for wxPython. |
| 26 |
""" |
| 27 |
langdirs = [os.path.join(dir_, "lang") for dir_ in DATA_DIRS] |
| 28 |
for langdir in langdirs: |
| 29 |
if not os.path.exists(langdir) or not os.path.isdir(langdir): |
| 30 |
continue |
| 31 |
try: |
| 32 |
langfiles = os.listdir(langdir) |
| 33 |
except Exception as exception: |
| 34 |
print(f"Warning - directory '{langdir}' listing failed: {exception}") |
| 35 |
else: |
| 36 |
for filename in langfiles: |
| 37 |
name, ext = os.path.splitext(filename) |
| 38 |
if ext.lower() == ".yaml" and name.lower() not in LDICT: |
| 39 |
path = os.path.join(langdir, filename) |
| 40 |
LDICT[name.lower()] = LazyDictYAMLUltraLite(path) |
| 41 |
if len(LDICT) == 0: |
| 42 |
handle_error( |
| 43 |
UserWarning( |
| 44 |
"Warning: No language files found. The " |
| 45 |
"following places have been searched:\n{}".format("\n".join(langdirs)) |
| 46 |
) |
| 47 |
) |
| 48 |
|
| 49 |
|
| 50 |
def update_defaults() -> None: |
| 51 |
"""Update default paths in the DEFAULTS dictionary.""" |
| 52 |
DEFAULTS.update( |
| 53 |
{ |
| 54 |
"last_3dlut_path": os.path.join(expanduseru("~"), getstr("unnamed")), |
| 55 |
"last_archive_save_path": os.path.join(expanduseru("~"), getstr("unnamed")), |
| 56 |
"last_cal_path": os.path.join(STORAGE, getstr("unnamed")), |
| 57 |
"last_cal_or_icc_path": os.path.join(STORAGE, getstr("unnamed")), |
| 58 |
"last_colorimeter_ti3_path": os.path.join( |
| 59 |
expanduseru("~"), getstr("unnamed") |
| 60 |
), |
| 61 |
"last_testchart_export_path": os.path.join( |
| 62 |
expanduseru("~"), getstr("unnamed") |
| 63 |
), |
| 64 |
"last_filedialog_path": os.path.join(expanduseru("~"), getstr("unnamed")), |
| 65 |
"last_icc_path": os.path.join(STORAGE, getstr("unnamed")), |
| 66 |
"last_reference_ti3_path": os.path.join( |
| 67 |
expanduseru("~"), getstr("unnamed") |
| 68 |
), |
| 69 |
"last_ti1_path": os.path.join(STORAGE, getstr("unnamed")), |
| 70 |
"last_ti3_path": os.path.join(STORAGE, getstr("unnamed")), |
| 71 |
"last_vrml_path": os.path.join(STORAGE, getstr("unnamed")), |
| 72 |
} |
| 73 |
) |
| 74 |
|
| 75 |
|
| 76 |
def getcode() -> str: |
| 77 |
"""Get language code from config. |
| 78 |
|
| 79 |
Returns: |
| 80 |
str: The language code, falling back to defaults if not set or found. |
| 81 |
""" |
| 82 |
lcode = getcfg("lang") |
| 83 |
if lcode not in LDICT: |
| 84 |
# fall back to default |
| 85 |
lcode = DEFAULTS["lang"] |
| 86 |
if lcode not in LDICT: |
| 87 |
# fall back to english |
| 88 |
lcode = "en" |
| 89 |
return lcode |
| 90 |
|
| 91 |
|
| 92 |
def getstr( |
| 93 |
id_str: str, |
| 94 |
strvars: None | str | list | tuple = None, |
| 95 |
lcode: None | str = None, |
| 96 |
default: None | str = None, |
| 97 |
) -> str: |
| 98 |
"""Get a translated string from the dictionary. |
| 99 |
|
| 100 |
Args: |
| 101 |
id_str (str): The identifier for the string to be translated. |
| 102 |
strvars (None | str | list | tuple, optional): Variables to format the |
| 103 |
string with. |
| 104 |
lcode (None | str, optional): Language code to use for translation. If |
| 105 |
None, uses the current language code from config. |
| 106 |
default (None | str, optional): Default string to return if translation |
| 107 |
is not found. |
| 108 |
|
| 109 |
Returns: |
| 110 |
str: The translated string if found, otherwise the default or |
| 111 |
identifier. |
| 112 |
""" |
| 113 |
lcode = lcode if lcode else getcode() |
| 114 |
if lcode not in LDICT or id_str not in LDICT[lcode]: |
| 115 |
# fall back to english |
| 116 |
lcode = "en" |
| 117 |
if lcode in LDICT and id_str in LDICT[lcode]: |
| 118 |
lstr = LDICT[lcode][id_str] |
| 119 |
if DEBUG: |
| 120 |
if id_str not in usage or not isinstance(usage[id_str], int): |
| 121 |
usage[id_str] = 1 |
| 122 |
else: |
| 123 |
usage[id_str] += 1 |
| 124 |
if strvars is not None: |
| 125 |
strvars = [strvars] if not isinstance(strvars, (list, tuple)) else strvars |
| 126 |
fmt = re.findall(r"%\d?(?:\.\d+)?[deEfFgGiorsxX]", lstr) |
| 127 |
if len(fmt) == len(strvars): |
| 128 |
strvars = list(strvars) if not isinstance(strvars, list) else strvars |
| 129 |
for i, s in enumerate(strvars): |
| 130 |
if fmt[i].endswith("s"): |
| 131 |
s = str(s) |
| 132 |
elif not fmt[i].endswith("r"): |
| 133 |
try: |
| 134 |
s = int(s) if fmt[i][-1] in "dioxX" else float(s) |
| 135 |
except (TypeError, ValueError): |
| 136 |
s = 0 |
| 137 |
strvars[i] = s |
| 138 |
lstr %= tuple(strvars) |
| 139 |
return lstr |
| 140 |
if DEBUG and id_str and not isinstance(id_str, str) and " " not in id_str: |
| 141 |
usage[id_str] = 0 |
| 142 |
return default or id_str |
| 143 |
|
| 144 |
|
| 145 |
def gettext(text: str) -> str: |
| 146 |
"""Get a translated string from the dictionary. |
| 147 |
|
| 148 |
Args: |
| 149 |
text (str): The text to be translated. |
| 150 |
|
| 151 |
Returns: |
| 152 |
str: The translated string if found, otherwise the original text. |
| 153 |
""" |
| 154 |
if not CATALOG and DEFAULTS["lang"] in LDICT: |
| 155 |
for id_str in LDICT[DEFAULTS["lang"]]: |
| 156 |
lstr = LDICT[DEFAULTS["lang"]][id_str] |
| 157 |
CATALOG[lstr] = {} |
| 158 |
CATALOG[lstr].id_str = id_str |
| 159 |
lcode = getcode() |
| 160 |
if CATALOG and text in CATALOG and lcode not in CATALOG[text]: |
| 161 |
CATALOG[text][lcode] = LDICT[lcode].get(CATALOG[text].id_str, text) |
| 162 |
return CATALOG.get(text, {}).get(lcode, text) |
| 163 |
|
| 164 |
|
| 165 |
LDICT = {} |
| 166 |
CATALOG = {} |
| 167 |
|
| 168 |
|
| 169 |
if DEBUG: |
| 170 |
import atexit |
| 171 |
|
| 172 |
from DisplayCAL.config import CONFIG_HOME |
| 173 |
from DisplayCAL.jsondict import JSONDict |
| 174 |
|
| 175 |
usage = JSONDict() |
| 176 |
usage_path = os.path.join(CONFIG_HOME, "localization_usage.json") |
| 177 |
if os.path.isfile(usage_path): |
| 178 |
usage.path = usage_path |
| 179 |
|
| 180 |
def write_usage() -> None: |
| 181 |
"""Write localization usage to file on exit.""" |
| 182 |
global usage |
| 183 |
if not usage: |
| 184 |
return |
| 185 |
if os.path.isfile(usage_path): |
| 186 |
temp = JSONDict(usage_path) |
| 187 |
temp.load() |
| 188 |
temp.update(usage) |
| 189 |
usage = temp |
| 190 |
with open(usage_path, "wb") as usagefile: |
| 191 |
usagefile.write(b"{\n") |
| 192 |
for key, count in sorted(usage.items()): |
| 193 |
usagefile.write(b'\t"%s": %i,\n' % (key.encode("UTF-8"), count)) |
| 194 |
usagefile.write(b"}") |
| 195 |
|
| 196 |
atexit.register(write_usage) |