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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
|
#!/usr/bin/env python
from __future__ import print_function
import json
import os
import io
import sys
from font import getFontMap
TRANSLATION_CPP = "Translation.cpp"
try:
to_unicode = unicode
except NameError:
to_unicode = str
# Loading a single JSON file
def loadJson(fileName, skipFirstLine):
with io.open(fileName, mode="r", encoding="utf-8") as f:
if skipFirstLine:
f.readline()
obj = json.loads(f.read())
return obj
# Reading all language translations into a dictionary by langCode
def readTranslations(jsonDir):
langDict = {}
# Read all translation files from the input dir
for fileName in os.listdir(jsonDir):
fileWithPath = os.path.join(jsonDir, fileName)
lf = fileName.lower()
# Read only translation_XX.json
if lf.startswith("translation_") and lf.endswith(".json"):
try:
lang = loadJson(fileWithPath, False)
except json.decoder.JSONDecodeError as e:
print("Failed to decode " + lf)
print(str(e))
sys.exit(2)
# Extract lang code from file name
langCode = fileName[12:-5].upper()
# ...and the one specified in the JSON file...
try:
langCodeFromJson = lang['languageCode']
except KeyError:
langCodeFromJson = "(missing)"
# ...cause they should be the same!
if langCode != langCodeFromJson:
raise ValueError("Invalid languageCode " + langCodeFromJson +
" in file " + fileName)
langDict[langCode] = lang
return langDict
def writeStart(f):
f.write(
to_unicode(
"""// WARNING: THIS FILE WAS AUTO GENERATED BY make_translation.py. PLEASE DO NOT EDIT.
#include "Translation.h"
#ifndef LANG
#define LANG_EN
#endif
"""))
def escapeC(s):
return s.replace("\"", "\\\"")
def getLetterCounts(defs, lang):
textList = []
#iterate over all strings
obj = lang['menuOptions']
for mod in defs['menuOptions']:
eid = mod['id']
textList.append(obj[eid]['desc'])
# collapse all strings down into the composite letters and store totals for these
symbolCounts = {}
for line in textList:
for letter in line:
symbolCounts[letter] = symbolCounts.get(letter, 0) + 1
symbolCounts = sorted(
symbolCounts.items(),
key=lambda kv: kv[1]) # swap to Big -> little sort order
symbolCounts = list(map(lambda x: x[0], symbolCounts))
symbolCounts.reverse()
return symbolCounts
def getFontMapAndTable(textList):
# the text list is sorted
# allocate out these in their order as number codes
symbolMap = {}
index = 1
for sym in textList:
symbolMap[sym] = "\\x%0.2X" % index
index = index + 1
# Get the font table
fontTableStrings = []
fontTable = getFontMap()
for sym in textList:
if sym not in fontTable:
print(f'Missing font element for {sym}')
exit(1)
fontLine = fontTable[sym]
fontTableStrings.append(fontLine)
outputTable = "const uint8_t userFont_12[] = {" + to_unicode("\n")
for line in fontTableStrings:
# join font table int one large string
outputTable = outputTable + line + to_unicode("\n")
outputTable = outputTable + "};" + to_unicode("\n")
return (outputTable, symbolMap)
def convStr(symbolConversionTable,text):
# convert all of the symbols from the string into escapes for their content
outputString = ""
for c in text:
if c not in symbolConversionTable:
print(f'Missing font definition for {c}')
else:
outputString = outputString + symbolConversionTable[c]
return outputString
def writeLanguage(languageCode, defs, f):
print("Generating block for " + languageCode)
lang = langDict[languageCode]
#Iterate over all of the text to build up the symbols & counts
textList = getLetterCounts(defs, lang)
# From the letter counts, need to make a symbol translator & write out the font
(fontTableText, symbolConversionTable) = getFontMapAndTable(textList)
f.write(to_unicode("\n#ifdef LANG_" + languageCode + "\n"))
f.write(fontTableText)
try:
langName = lang['languageLocalName']
except KeyError:
langName = languageCode
f.write(to_unicode("// ---- " + langName + " ----\n\n"))
try:
cyrillic = lang['cyrillicGlyphs']
except KeyError:
cyrillic = False
if cyrillic:
f.write(to_unicode("#define CYRILLIC_GLYPHS\n\n"))
# ----- Writing SettingsDescriptions
obj = lang['menuOptions']
f.write(to_unicode("const char* SettingsDescriptions[] = {\n"))
maxLen = 25
for mod in defs['menuOptions']:
eid = mod['id']
if 'feature' in mod:
f.write(to_unicode("#ifdef " + mod['feature'] + "\n"))
f.write(to_unicode(" /* " + eid.ljust(maxLen)[:maxLen] + " */ "))
f.write(to_unicode("\"" + convStr(symbolConversionTable,(obj[eid]['desc'])) + "\",\n"))
if 'feature' in mod:
f.write(to_unicode("#endif\n"))
f.write(to_unicode("};\n\n"))
# ----- Writing Message strings
obj = lang['messages']
for mod in defs['messages']:
eid = mod['id']
f.write(
to_unicode("const char* " + eid + " = \"" + convStr(symbolConversionTable,(obj[eid])) +
"\";\n"))
f.write(to_unicode("\n"))
# ----- Writing Characters
obj = lang['characters']
for mod in defs['characters']:
eid = mod['id']
f.write(to_unicode("const char* " + eid + " = '" + convStr(symbolConversionTable,obj[eid]) + "';\n"))
f.write(to_unicode("\n"))
# ----- Menu Options
# Menu type
f.write(
to_unicode(
"const enum ShortNameType SettingsShortNameType = SHORT_NAME_" +
("DOUBLE" if lang['menuDouble'] else "SINGLE") + "_LINE;\n"))
# ----- Writing SettingsDescriptions
obj = lang['menuOptions']
f.write(to_unicode("const char* SettingsShortNames[][2] = {\n"))
maxLen = 25
for mod in defs['menuOptions']:
eid = mod['id']
if 'feature' in mod:
f.write(to_unicode("#ifdef " + mod['feature'] + "\n"))
f.write(to_unicode(" /* " + eid.ljust(maxLen)[:maxLen] + " */ "))
if lang['menuDouble']:
f.write(
to_unicode("{ \"" + convStr(symbolConversionTable,(obj[eid]['text2'][0])) + "\", \"" +
convStr(symbolConversionTable,(obj[eid]['text2'][1])) + "\" },\n"))
else:
f.write(to_unicode("{ \"" + convStr(symbolConversionTable,(obj[eid]['text'])) + "\" },\n"))
if 'feature' in mod:
f.write(to_unicode("#endif\n"))
f.write(to_unicode("};\n\n"))
# ----- Writing Menu Groups
obj = lang['menuGroups']
f.write(
to_unicode("const char* SettingsMenuEntries[" + str(len(obj)) +
"] = {\n"))
maxLen = 25
for mod in defs['menuGroups']:
eid = mod['id']
f.write(to_unicode(" /* " + eid.ljust(maxLen)[:maxLen] + " */ "))
f.write(
to_unicode("\"" + convStr(symbolConversionTable,(obj[eid]['text2'][0]) + "\\n" +
obj[eid]['text2'][1]) + "\",\n"))
f.write(to_unicode("};\n\n"))
# ----- Writing Menu Groups Descriptions
obj = lang['menuGroups']
f.write(
to_unicode("const char* SettingsMenuEntriesDescriptions[" +
str(len(obj)) + "] = {\n"))
maxLen = 25
for mod in defs['menuGroups']:
eid = mod['id']
f.write(to_unicode(" /* " + eid.ljust(maxLen)[:maxLen] + " */ "))
f.write(to_unicode("\"" + convStr(symbolConversionTable,(obj[eid]['desc'])) + "\",\n"))
f.write(to_unicode("};\n\n"))
# ----- Block end
f.write(to_unicode("#endif\n"))
def read_opts():
""" Reading input parameters
First parameter = json directory
Second parameter = target directory
"""
if len(sys.argv) > 1:
jsonDir = sys.argv[1]
else:
jsonDir = "."
if len(sys.argv) > 2:
outFile = sys.argv[2]
else:
outDir = os.path.relpath(jsonDir + "/../workspace/TS100/src/")
outFile = os.path.join(outDir, TRANSLATION_CPP)
if len(sys.argv) > 3:
raise Exception("Too many parameters!")
return jsonDir, outFile
def orderOutput(langDict):
# These languages go first
mandatoryOrder = ['EN']
# Then add all others in alphabetical order
sortedKeys = sorted(langDict.keys())
# Add the rest as they come
for key in sortedKeys:
if key not in mandatoryOrder:
mandatoryOrder.append(key)
return mandatoryOrder
def writeTarget(outFile, defs, langCodes):
# Start writing the file
with io.open(outFile, 'w', encoding='utf-8', newline="\n") as f:
writeStart(f)
for langCode in langCodes:
writeLanguage(langCode, defs, f)
if __name__ == "__main__":
try:
jsonDir, outFile = read_opts()
except:
print("usage: make_translation.py {json dir} {cpp dir}")
sys.exit(1)
print("Making " + outFile + " from " + jsonDir)
langDict = readTranslations(jsonDir)
defs = loadJson(os.path.join(jsonDir, "translations_def.js"), True)
langCodes = orderOutput(langDict)
writeTarget(outFile, defs, langCodes)
print("Done")
|