forked from trezor/trezor-firmware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translations.py
175 lines (136 loc) · 5.53 KB
/
translations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import json
import typing as t
from hashlib import sha256
from pathlib import Path
from trezorlib import cosi, device, models
from trezorlib._internal import translations
from trezorlib.debuglink import TrezorClientDebugLink as Client
from . import common
HERE = Path(__file__).resolve().parent
ROOT = HERE.parent
TRANSLATIONS = ROOT / "core" / "translations"
FONTS_DIR = TRANSLATIONS / "fonts"
ORDER_FILE = TRANSLATIONS / "order.json"
LANGUAGES = [file.stem for file in TRANSLATIONS.glob("??.json")]
def prepare_blob(
lang_or_def: translations.JsonDef | Path | str,
model: models.TrezorModel,
version: translations.VersionTuple | tuple[int, int, int] | None = None,
) -> translations.TranslationsBlob:
order = translations.order_from_json(json.loads(ORDER_FILE.read_text()))
if isinstance(lang_or_def, str):
lang_or_def = get_lang_json(lang_or_def)
if isinstance(lang_or_def, Path):
lang_or_def = t.cast(translations.JsonDef, json.loads(lang_or_def.read_text()))
# generate raw blob
if version is None:
version = translations.version_from_json(lang_or_def["header"]["version"])
elif len(version) == 3:
# version coming from client object does not have build item
version = *version, 0
return translations.blob_from_defs(lang_or_def, order, model, version, FONTS_DIR)
def sign_blob(blob: translations.TranslationsBlob) -> bytes:
# build 0-item Merkle proof
digest = sha256(b"\x00" + blob.header_bytes).digest()
signature = cosi.sign_with_privkeys(digest, common.PRIVATE_KEYS_DEV)
blob.proof = translations.Proof(
merkle_proof=[],
sigmask=0b111,
signature=signature,
)
return blob.build()
def build_and_sign_blob(
lang_or_def: translations.JsonDef | Path | str,
client: Client,
) -> bytes:
blob = prepare_blob(lang_or_def, client.model, client.version)
return sign_blob(blob)
def set_language(client: Client, lang: str):
if lang.startswith("en"):
language_data = b""
else:
language_data = build_and_sign_blob(lang, client)
with client:
device.change_language(client, language_data) # type: ignore
def get_lang_json(lang: str) -> translations.JsonDef:
assert lang in LANGUAGES
lang_json = json.loads((TRANSLATIONS / f"{lang}.json").read_text())
if (fonts_safe3 := lang_json.get("fonts", {}).get("##Safe3")) is not None:
lang_json["fonts"]["T2B1"] = fonts_safe3
lang_json["fonts"]["T3B1"] = fonts_safe3
return lang_json
def _get_all_language_data() -> list[dict[str, str]]:
return [_get_language_data(language) for language in LANGUAGES]
def _get_language_data(lang: str) -> dict[str, str]:
return get_lang_json(lang)["translations"]
all_language_data = _get_all_language_data()
def _resolve_path_to_texts(
path: str, template: t.Iterable[t.Any] = (), lower: bool = True
) -> list[str]:
texts: list[str] = []
lookups = path.split(".")
for language_data in all_language_data:
language_data_missing = False
data: dict[str, t.Any] | str = language_data
for lookup in lookups:
assert isinstance(data, dict), f"{lookup} is not a dict"
if lookup not in data:
language_data_missing = True
break
data = data[lookup]
if language_data_missing:
continue
assert isinstance(data, str), f"{path} is not a string"
if template:
data = data.format(*template)
texts.append(data)
if lower:
texts = [t.lower() for t in texts]
texts = [t.replace("\xa0", " ").strip() for t in texts]
return texts
def assert_equals(text: str, path: str, template: t.Iterable[t.Any] = ()) -> None:
# TODO: we can directly pass in the current device language
texts = _resolve_path_to_texts(path, template)
assert text.lower() in texts, f"{text} not found in {texts}"
def assert_equals_multiple(
text: str, paths: list[str], template: t.Iterable[t.Any] = ()
) -> None:
texts: list[str] = []
for path in paths:
texts += _resolve_path_to_texts(path, template)
assert text.lower() in texts, f"{text} not found in {texts}"
def assert_in(text: str, path: str, template: t.Iterable[t.Any] = ()) -> None:
texts = _resolve_path_to_texts(path, template)
for tt in texts:
if tt in text.lower():
return
assert False, f"{text} not found in {texts}"
def assert_in_multiple(
text: str, paths: list[str], template: t.Iterable[t.Any] = ()
) -> None:
texts: list[str] = []
for path in paths:
texts += _resolve_path_to_texts(path, template)
for tt in texts:
if tt in text.lower():
return
assert False, f"{text} not found in {texts}"
def assert_startswith(text: str, path: str, template: t.Iterable[t.Any] = ()) -> None:
texts = _resolve_path_to_texts(path, template)
for tt in texts:
if text.lower().startswith(tt):
return
assert False, f"{text} not found in {texts}"
def assert_template(text: str, template_path: str) -> None:
templates = _resolve_path_to_texts(template_path)
for tt in templates:
# Checking at least the first part
first_part = tt.split("{")[0]
if text.lower().startswith(first_part):
return
assert False, f"{text} not found in {templates}"
def translate(
path: str, template: t.Iterable[t.Any] = (), lower: bool = False
) -> list[str]:
# Do not converting to lowercase, we want the exact value
return _resolve_path_to_texts(path, template, lower=lower)