-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgenerate_ui.py
429 lines (281 loc) · 16.4 KB
/
generate_ui.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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
"""Generates code and configuration files for indicators and meters based on the specifications in
source/indicators.json and source/meters.json."""
import json
import re
GENERATED_FILE_WARNING = "This is a generated file. Do not edit manually or suffer the consequences..."
# #
# # ##### # # # ##### # ###### ####
# # # # # # # # # #
# # # # # # # # ##### ####
# # # # # # # # # #
# # # # # # # # # # #
##### # # ###### # # # ###### ####
def add_index_field(items):
"""Adds an index field to all dictionaries in the given list of dictionaries."""
for index, item in enumerate(items):
item["index"] = index
def sorted_by_localized_name(items):
"""Returns a view on the given items that is sorted by their English language names."""
return sorted(
items,
key=lambda item: item["languages"]["en"])
def to_file_name_suffix(config):
"""Generates the suffix to be used for output files."""
return F"_{config['category'].lower()}s"
def to_drawable_id(config, id):
"""Generates an identifier to be used for the given drawable ID."""
return F"{config['category']}{id}"
def to_behavior_id(config, id):
"""Generates an identifier to be used for the given behavior ID."""
return F"{config['category']}Behavior{id}"
def item_with_id(items, id):
"""From the given list of items, returns the item with the given ID or None if there is... well... none."""
for item in items:
if item["id"] == id:
return item
else:
return None
def to_constant_name(id):
"""Turns an ID into a constant name (snake and upper case)."""
# See https://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case
# Take care of capital letters followed by non-capitals (except at string start); precede with underscore.
id = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', id)
# Insert remaining required underscores
id = re.sub('([a-z0-9])([A-Z])', r'\1_\2', id)
return id.upper()
######
# # ##### ## # # ## ##### # ###### ####
# # # # # # # # # # # # # # #
# # # # # # # # # # ##### # ##### ####
# # ##### ###### # ## # ###### # # # # #
# # # # # # ## ## # # # # # # # #
###### # # # # # # # # ##### ###### ###### ####
def generate_drawables(config):
"""Generate the drawables for the given config."""
file_name = F"resources/drawables/drawables{to_file_name_suffix(config)}.xml"
print(F"Generating drawables: {file_name}")
with open(file_name, mode="w", encoding="utf8", newline="\n") as out_file:
print(F"<!-- {GENERATED_FILE_WARNING} -->", file=out_file)
print(F"<drawables>", file=out_file)
# We need to generate a drawable for each behavior
for behavior in config["behaviors"]:
behaviorId = to_behavior_id(config, behavior["id"])
print(F' <bitmap id="{behaviorId}" filename="icon_Behavior{behavior["id"]}.png" />', file=out_file)
print(F"</drawables>", file=out_file)
#####
# # ##### ##### # # # #### ####
# # # # # ## # # # #
##### # # # # # # # # ####
# # ##### # # # # # ### #
# # # # # # # ## # # # #
##### # # # # # # #### ####
def assemble_languages(config):
"""Assembles all language codes used in the given config."""
# We always want English
language_codes = { "en" }
for drawable in config["drawables"]:
for language_code in drawable["languages"]:
language_codes.add(language_code)
for behavior in config["behaviors"]:
for language_code in behavior["languages"]:
language_codes.add(language_code)
return language_codes
def generate_string(item, item_id, language_code, out_file):
# Check if this item has a translation
if not language_code in item["languages"]:
print(F"{item_id} has no translation for {language_code}")
else:
print(F' <string id="{item_id}">{item["languages"][language_code]}</string>', file=out_file)
def generate_strings(config):
"""Generates language definitions for the given config."""
for language_code in assemble_languages(config):
dir_name = "resources"
if language_code != "en":
dir_name += F"-{language_code}"
file_name = F"{dir_name}/strings/strings{to_file_name_suffix(config)}.xml"
print(F"Generating strings for language code {language_code}: {file_name}")
with open(file_name, mode="w", encoding="utf8", newline="\n") as out_file:
print(F"<!-- {GENERATED_FILE_WARNING} -->", file=out_file)
print("<strings>", file=out_file)
# We need to generate a string for each drawable
print(" <!-- Drawables -->", file=out_file)
for drawable in config["drawables"]:
drawableId = to_drawable_id(config, drawable["id"])
generate_string(drawable, drawableId, language_code, out_file)
print("", file=out_file)
print(" <!-- Behaviors -->", file=out_file)
for behavior in config["behaviors"]:
behaviorId = to_behavior_id(config, behavior["id"])
generate_string(behavior, behaviorId, language_code, out_file)
print("</strings>", file=out_file)
# #
## ## ###### # # # # ####
# # # # # ## # # # #
# # # ##### # # # # # ####
# # # # # # # # #
# # # # ## # # # #
# # ###### # # #### ####
def generate_menus(config):
"""Generates a selection menu for the available behaviors, sorted by English name."""
file_name = F"resources/menu/settingsMenu{config['category']}Selection.xml"
print(F"Generating menus: {file_name}")
with open(file_name, mode="w", encoding="utf8", newline="\n") as out_file:
print(F"<!-- {GENERATED_FILE_WARNING} -->", file=out_file)
print(F'<menu2 id="SettingsMenu{config["category"]}Selection" title="@Strings.{config["category"]}">', file=out_file)
print(F' <menu-item id="{to_behavior_id(config, "Nothing")}" label="@Strings.Nothing" />', file=out_file)
for behavior in sorted_by_localized_name(config["behaviors"]):
behavior_id = to_behavior_id(config, behavior["id"])
print(F' <icon-menu-item id="{behavior_id}" label="@Strings.{behavior_id}" icon="@Drawables.{behavior_id}" />', file=out_file)
print('</menu2>', file=out_file)
#####
# # ###### ##### ##### # # # #### ####
# # # # # ## # # # #
##### ##### # # # # # # # ####
# # # # # # # # # ### #
# # # # # # # ## # # # #
##### ###### # # # # # #### ####
def generate_properties(config):
"""Generate property files for the given configuration, including proper default values."""
file_name = F"resources/settings/properties{to_file_name_suffix(config)}.xml"
print(F"Generating properties: {file_name}")
with open(file_name, mode="w", encoding="utf8", newline="\n") as out_file:
print(F"<!-- {GENERATED_FILE_WARNING} -->", file=out_file)
print("<properties>", file=out_file)
for drawable in config["drawables"]:
drawable_id = to_drawable_id(config, drawable["id"])
default_behavior = item_with_id(config["behaviors"], drawable["defaultBehavior"])
print(F' <property id="{drawable_id}" type="number">{default_behavior["index"]}</property> <!-- {default_behavior["id"]} -->', file=out_file)
print('</properties>', file=out_file)
def generate_settings_behvaior_list(config, exclude_behaviors_that_require_text):
"""Generates the proper settingConfig for the behaviors in the given config."""
result = ' <settingConfig type="list">\n'
result += ' <listEntry value="-1">@Strings.Nothing</listEntry>\n'
for behavior in sorted_by_localized_name(config["behaviors"]):
if not exclude_behaviors_that_require_text or behavior["worksWithoutText"]:
behavior_id = to_behavior_id(config, behavior["id"])
result += F' <listEntry value="{behavior["index"]}">@Strings.{behavior_id}</listEntry>\n'
result += ' </settingConfig>'
return result
def generate_settings(config):
"""Generate settings files for the given configuration, including properly sorted value lists."""
file_name = F"resources/settings/settings{to_file_name_suffix(config)}.xml"
print(F"Generating settings: {file_name}")
with open(file_name, mode="w", encoding="utf8", newline="\n") as out_file:
print(F"<!-- {GENERATED_FILE_WARNING} -->", file=out_file)
print("<settings>", file=out_file)
for drawable in config["drawables"]:
drawable_id = to_drawable_id(config, drawable["id"])
# If the drawable can display text, we'll assemble a list of all behaviors. If not, we must
# exclude those behaviors that do not work without text
behavior_list = generate_settings_behvaior_list(config, not drawable["displaysText"])
print(F' <setting propertyKey="@Properties.{drawable_id}" title="@Strings.{drawable_id}">', file=out_file)
print(behavior_list, file=out_file)
print(' </setting>', file=out_file)
print('</settings>', file=out_file)
#####
# # #### # # #### ##### ## # # ##### ####
# # # ## # # # # # ## # # #
# # # # # # #### # # # # # # # ####
# # # # # # # # ###### # # # # #
# # # # # ## # # # # # # ## # # #
##### #### # # #### # # # # # # ####
def generate_count_constants(config, out_file):
"""Generates name-related constants and writes them to the given output file."""
print(F"const {to_constant_name(config['category'] + 'Count')} = {len(config['drawables'])};", file=out_file)
print(F"const {to_constant_name(config['category'] + 'BehaviorCount')} = {len(config['behaviors'])};", file=out_file)
print("", file=out_file)
def generate_name_constants(config, out_file):
"""Generates name-related constants and writes them to the given output file."""
# Generate the names of the drawables
print(F"const {to_constant_name(config['category'] + 'Names')} = [", file=out_file)
drawable_strings = ',\n '.join( [ F'"{to_drawable_id(config, drawable["id"])}"' for drawable in config["drawables"] ] )
print(F" {drawable_strings}", file=out_file)
print("];\n", file=out_file)
# Generate the names of the behaviors
print(F"const {to_constant_name(config['category'] + 'BehaviorNames')} = [", file=out_file)
behavior_strings = ',\n '.join( [ F'"{to_behavior_id(config, behavior["id"])}"' for behavior in config["behaviors"] ] )
print(F" {behavior_strings}", file=out_file)
print("];\n", file=out_file)
def generate_enum_constants(config, out_file):
"""Generates enumeration-related constants and writes them to the given output file."""
# Generate enumerations of the drawables
print(F"enum /* {config['category'].upper()} */ " + "{", file=out_file)
drawable_constants = ',\n '.join( [ to_constant_name(to_drawable_id(config, drawable["id"])) for drawable in config["drawables"] ] )
print(F" {drawable_constants}", file=out_file)
print("}\n", file=out_file)
# Generate enumerations of the behaviors
print(F"enum /* {config['category'].upper()}_BEHAVIORS */ " + "{", file=out_file)
behavior_constants = ',\n '.join( [ to_constant_name(to_behavior_id(config, behavior["id"])) for behavior in config["behaviors"] ] )
print(F" {behavior_constants}", file=out_file)
print("}\n", file=out_file)
def generate_resource_map(config, out_file):
"""Generates arrays that will map drawable and behavior IDs to the string resource ID
that contains the properly localized name."""
# Generate resource map of the drawables
print(F"const {to_constant_name(config['category'] + 'ToStringResource')} = [", file=out_file)
drawable_resources = ',\n '.join( [ F'Rez.Strings.{to_drawable_id(config, drawable["id"])}' for drawable in config["drawables"] ] )
print(F" {drawable_resources}", file=out_file)
print("];\n", file=out_file)
# Generate resource map of the behaviors
print(F"const {to_constant_name(config['category'] + 'BehaviorToStringResource')} = [", file=out_file)
behavior_resources = ',\n '.join( [ F'Rez.Strings.{to_behavior_id(config, behavior["id"])}' for behavior in config["behaviors"] ] )
print(F" {behavior_resources}", file=out_file)
print("];\n", file=out_file)
def generate_factories(config, out_file):
"""Generates behavior factory functions."""
print("/**", file=out_file)
print(" * Turns a behavior ID into an instance of the class that implements the behavior.", file=out_file)
print(" */", file=out_file)
print(F"function create{config['category']}Behavior(id)" + " {", file=out_file)
print(" switch (id) {", file=out_file)
for behavior in config["behaviors"]:
behavior_id = to_behavior_id(config, behavior["id"])
print(F" case {to_constant_name(behavior_id)}:", file=out_file)
print(F" return new {behavior_id}();", file=out_file)
print(" default:", file=out_file)
print(" return null;", file=out_file)
print(" }", file=out_file)
print("}\n", file=out_file)
def generate_constants(config):
"""Generates a file with a whole bunch of constants that may come in handy."""
file_name = F"source/generated/{(config['category'])}s.mc"
print(F"Generating constants: {file_name}")
with open(file_name, mode="w", encoding="utf8", newline="\n") as out_file:
print(F"// {GENERATED_FILE_WARNING}", file=out_file)
print("", file=out_file)
print("module FaceyMcWatchface {", file=out_file)
print(F"module {config['category']}s " + "{", file=out_file)
print("", file=out_file)
print("// Number of things and behaviors", file=out_file);
generate_count_constants(config, out_file)
print("// Enumerations of available things and behaviors to index into the other arrays", file=out_file)
generate_enum_constants(config, out_file)
print("// Names used in all sorts of properties, settings, drawables...", file=out_file)
generate_name_constants(config, out_file)
print("// String resource IDs that belong to things. Use these to generate names in the UI.", file=out_file)
generate_resource_map(config, out_file)
generate_factories(config, out_file)
print("} }", file=out_file)
# # #####
## ## ## # # # # # #### ##### # ##### #####
# # # # # # # ## # # # # # # # # # #
# # # # # # # # # ##### # # # # # # #
# # ###### # # # # # # ##### # ##### #
# # # # # # ## # # # # # # # # #
# # # # # # # ##### #### # # # # #
# Our configuration files
config_files = [ "indicators", "meters" ]
for file in config_files:
with open(F"source/{file}.json") as json_file:
config = json.load(json_file)
print(config["category"])
# We will probably shuffle lists around, so remember the original order
add_index_field(config["drawables"])
add_index_field(config["behaviors"])
# Generate all the code we need
generate_drawables(config)
generate_strings(config)
generate_menus(config)
generate_properties(config)
generate_settings(config)
generate_constants(config)