Debian Codegraph @

intl/core_option_translation.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 """Core options text extractor
4
5 The purpose of this script is to set up & provide functions for automatic generation of 'libretro_core_options_intl.h'
6 from 'libretro_core_options.h' using translations from Crowdin.
7
8 Both v1 and v2 structs are supported. It is, however, recommended to convert v1 files to v2 using the included
9 'v1_to_v2_converter.py'.
10
11 Usage:
12 python3 path/to/core_option_translation.py "path/to/where/libretro_core_options.h & libretro_core_options_intl.h/are" "core_name"
13
14 This script will:
15 1.) create key words for & extract the texts from libretro_core_options.h & save them into intl/_us/core_options.h
16 2.) do the same for any present translations in libretro_core_options_intl.h, saving those in their respective folder
17 """
18 import core_option_regex as cor
19 import re
20 import os
21 import sys
22 import json
23 import urllib.request as req
24 import shutil
25
26 # LANG_CODE_TO_R_LANG = {'_ar': 'RETRO_LANGUAGE_ARABIC',
27 # '_ast': 'RETRO_LANGUAGE_ASTURIAN',
28 # '_chs': 'RETRO_LANGUAGE_CHINESE_SIMPLIFIED',
29 # '_cht': 'RETRO_LANGUAGE_CHINESE_TRADITIONAL',
30 # '_cs': 'RETRO_LANGUAGE_CZECH',
31 # '_cy': 'RETRO_LANGUAGE_WELSH',
32 # '_da': 'RETRO_LANGUAGE_DANISH',
33 # '_de': 'RETRO_LANGUAGE_GERMAN',
34 # '_el': 'RETRO_LANGUAGE_GREEK',
35 # '_eo': 'RETRO_LANGUAGE_ESPERANTO',
36 # '_es': 'RETRO_LANGUAGE_SPANISH',
37 # '_fa': 'RETRO_LANGUAGE_PERSIAN',
38 # '_fi': 'RETRO_LANGUAGE_FINNISH',
39 # '_fr': 'RETRO_LANGUAGE_FRENCH',
40 # '_gl': 'RETRO_LANGUAGE_GALICIAN',
41 # '_he': 'RETRO_LANGUAGE_HEBREW',
42 # '_hu': 'RETRO_LANGUAGE_HUNGARIAN',
43 # '_id': 'RETRO_LANGUAGE_INDONESIAN',
44 # '_it': 'RETRO_LANGUAGE_ITALIAN',
45 # '_ja': 'RETRO_LANGUAGE_JAPANESE',
46 # '_ko': 'RETRO_LANGUAGE_KOREAN',
47 # '_nl': 'RETRO_LANGUAGE_DUTCH',
48 # '_oc': 'RETRO_LANGUAGE_OCCITAN',
49 # '_pl': 'RETRO_LANGUAGE_POLISH',
50 # '_pt_br': 'RETRO_LANGUAGE_PORTUGUESE_BRAZIL',
51 # '_pt_pt': 'RETRO_LANGUAGE_PORTUGUESE_PORTUGAL',
52 # '_ru': 'RETRO_LANGUAGE_RUSSIAN',
53 # '_sk': 'RETRO_LANGUAGE_SLOVAK',
54 # '_sv': 'RETRO_LANGUAGE_SWEDISH',
55 # '_tr': 'RETRO_LANGUAGE_TURKISH',
56 # '_uk': 'RETRO_LANGUAGE_UKRAINIAN',
57 # '_us': 'RETRO_LANGUAGE_ENGLISH',
58 # '_vn': 'RETRO_LANGUAGE_VIETNAMESE'}
59
60 # these are handled by RetroArch directly - no need to include them in core translations
61 ON_OFFS = {'"enabled"', '"disabled"', '"true"', '"false"', '"on"', '"off"'}
62
63
64 def remove_special_chars(text: str, char_set=0, allow_non_ascii=False) -> str:
65 """Removes special characters from a text.
66
67 :param text: String to be cleaned.
68 :param char_set: 0 -> remove all ASCII special chars except for '_' & 'space' (default)
69 1 -> remove invalid chars from file names
70 :param allow_non_ascii: False -> all non-ascii characters will be removed (default)
71 True -> non-ascii characters will be passed through
72 :return: Clean text.
73 """
74 command_chars = [chr(unicode) for unicode in tuple(range(0, 32)) + (127,)]
75 special_chars = ([chr(unicode) for unicode in tuple(range(33, 48)) + tuple(range(58, 65)) + tuple(range(91, 95))
76 + (96,) + tuple(range(123, 127))],
77 ('\\', '/', ':', '*', '?', '"', '<', '>', '|', '#', '%',
78 '&', '{', '}', '$', '!', '¸', "'", '@', '+', '='))
79 res = text if allow_non_ascii \
80 else text.encode('ascii', errors='ignore').decode('unicode-escape')
81
82 for cm in command_chars:
83 res = res.replace(cm, '_')
84 for sp in special_chars[char_set]:
85 res = res.replace(sp, '_')
86 while res.startswith('_'):
87 res = res[1:]
88 while res.endswith('_'):
89 res = res[:-1]
90 return res
91
92
93 def clean_file_name(file_name: str) -> str:
94 """Removes characters which might make file_name inappropriate for files on some OS.
95
96 :param file_name: File name to be cleaned.
97 :return: The clean file name.
98 """
99 file_name = remove_special_chars(file_name, 1)
100 file_name = re.sub(r'__+', '_', file_name.replace(' ', '_'))
101 return file_name
102
103
104 def get_struct_type_name(decl: str) -> tuple:
105 """ Returns relevant parts of the struct declaration:
106 type, name of the struct and the language appendix, if present.
107 :param decl: The struct declaration matched by cor.p_type_name.
108 :return: Tuple, e.g.: ('retro_core_option_definition', 'option_defs_us', '_us')
109 """
110 struct_match = cor.p_type_name.search(decl)
111 if struct_match:
112 if struct_match.group(3):
113 struct_type_name = struct_match.group(1, 2, 3)
114 return struct_type_name
115 elif struct_match.group(4):
116 struct_type_name = struct_match.group(1, 2, 4)
117 return struct_type_name
118 else:
119 struct_type_name = struct_match.group(1, 2)
120 return struct_type_name
121 else:
122 raise ValueError(f'No or incomplete struct declaration: {decl}!\n'
123 'Please make sure all structs are complete, including the type and name declaration.')
124
125
126 def is_viable_non_dupe(text: str, comparison) -> bool:
127 """text must be longer than 2 ('""'), not 'NULL' and not in comparison.
128
129 :param text: String to be tested.
130 :param comparison: Dictionary or set to search for text in.
131 :return: bool
132 """
133 return 2 < len(text) and text != 'NULL' and text not in comparison
134
135
136 def is_viable_value(text: str) -> bool:
137 """text must be longer than 2 ('""') and not 'NULL'.
138
139 :param text: String to be tested.
140 :return: bool
141 """
142 return 2 < len(text) and text != 'NULL'
143
144
145 def create_non_dupe(base_name: str, opt_num: int, comparison) -> str:
146 """Makes sure base_name is not in comparison, and if it is it's renamed.
147
148 :param base_name: Name to check/make unique.
149 :param opt_num: Number of the option base_name belongs to, used in making it unique.
150 :param comparison: Dictionary or set to search for base_name in.
151 :return: Unique name.
152 """
153 h = base_name
154 if h in comparison:
155 n = 0
156 h = h + '_O' + str(opt_num)
157 h_end = len(h)
158 while h in comparison:
159 h = h[:h_end] + '_' + str(n)
160 n += 1
161 return h
162
163
164 def get_texts(text: str) -> dict:
165 """Extracts the strings, which are to be translated/are the translations,
166 from text and creates macro names for them.
167
168 :param text: The string to be parsed.
169 :return: Dictionary of the form { '_<lang>': { 'macro': 'string', ... }, ... }.
170 """
171 # all structs: group(0) full struct, group(1) beginning, group(2) content
172 structs = cor.p_struct.finditer(text)
173 hash_n_string = {}
174 just_string = {}
175 for struct in structs:
176 struct_declaration = struct.group(1)
177 struct_type_name = get_struct_type_name(struct_declaration)
178 if 3 > len(struct_type_name):
179 lang = '_us'
180 else:
181 lang = struct_type_name[2]
182 if lang not in just_string:
183 hash_n_string[lang] = {}
184 just_string[lang] = set()
185 is_v2_definition = 'retro_core_option_v2_definition' == struct_type_name[0]
186 pre_name = ''
187 # info texts format
188 p = cor.p_info
189 if 'retro_core_option_v2_category' == struct_type_name[0]:
190 # prepend category labels, as they can be the same as option labels
191 pre_name = 'CATEGORY_'
192 # categories have different info texts format
193 p = cor.p_info_cat
194
195 struct_content = struct.group(4)
196 # 0: full option; 1: key; 2: description; 3: additional info; 4: key/value pairs
197 struct_options = cor.p_option.finditer(struct_content)
198 for opt, option in enumerate(struct_options):
199 # group 1: key
200 if option.group(1):
201 opt_name = pre_name + option.group(1)
202 # no special chars allowed in key
203 opt_name = remove_special_chars(opt_name).upper().replace(' ', '_')
204 else:
205 raise ValueError(f'No option name (key) found in struct {struct_type_name[1]} option {opt}!')
206
207 # group 2: description0
208 if option.group(2):
209 desc0 = option.group(2)
210 if is_viable_non_dupe(desc0, just_string[lang]):
211 just_string[lang].add(desc0)
212 m_h = create_non_dupe(re.sub(r'__+', '_', f'{opt_name}_LABEL'), opt, hash_n_string[lang])
213 hash_n_string[lang][m_h] = desc0
214 else:
215 raise ValueError(f'No label found in struct {struct_type_name[1]} option {option.group(1)}!')
216
217 # group 3: desc1, info0, info1, category
218 if option.group(3):
219 infos = option.group(3)
220 option_info = p.finditer(infos)
221 if is_v2_definition:
222 desc1 = next(option_info).group(1)
223 if is_viable_non_dupe(desc1, just_string[lang]):
224 just_string[lang].add(desc1)
225 m_h = create_non_dupe(re.sub(r'__+', '_', f'{opt_name}_LABEL_CAT'), opt, hash_n_string[lang])
226 hash_n_string[lang][m_h] = desc1
227 last = None
228 m_h = None
229 for j, info in enumerate(option_info):
230 last = info.group(1)
231 if is_viable_non_dupe(last, just_string[lang]):
232 just_string[lang].add(last)
233 m_h = create_non_dupe(re.sub(r'__+', '_', f'{opt_name}_INFO_{j}'), opt,
234 hash_n_string[lang])
235 hash_n_string[lang][m_h] = last
236 if last in just_string[lang]: # category key should not be translated
237 hash_n_string[lang].pop(m_h)
238 just_string[lang].remove(last)
239 else:
240 for j, info in enumerate(option_info):
241 gr1 = info.group(1)
242 if is_viable_non_dupe(gr1, just_string[lang]):
243 just_string[lang].add(gr1)
244 m_h = create_non_dupe(re.sub(r'__+', '_', f'{opt_name}_INFO_{j}'), opt,
245 hash_n_string[lang])
246 hash_n_string[lang][m_h] = gr1
247 else:
248 raise ValueError(f'Too few arguments in struct {struct_type_name[1]} option {option.group(1)}!')
249
250 # group 4: key/value pairs
251 if option.group(4):
252 for j, kv_set in enumerate(cor.p_key_value.finditer(option.group(4))):
253 set_key, set_value = kv_set.group(1, 2)
254 if not is_viable_value(set_value):
255 # use the key if value not available
256 set_value = set_key
257 if not is_viable_value(set_value):
258 continue
259 # re.fullmatch(r'(?:[+-][0-9]+)+', value[1:-1])
260
261 # add only if non-dupe, not translated by RetroArch directly & not purely numeric
262 if set_value not in just_string[lang]\
263 and set_value.lower() not in ON_OFFS\
264 and not re.sub(r'[+-]', '', set_value[1:-1]).isdigit():
265 clean_key = set_key[1:-1]
266 clean_key = remove_special_chars(clean_key).upper().replace(' ', '_')
267 m_h = create_non_dupe(re.sub(r'__+', '_', f"OPTION_VAL_{clean_key}"), opt, hash_n_string[lang])
268 hash_n_string[lang][m_h] = set_value
269 just_string[lang].add(set_value)
270 return hash_n_string
271
272
273 def create_msg_hash(intl_dir_path: str, core_name: str, keyword_string_dict: dict) -> dict:
274 """Creates '<core_name>.h' files in 'intl/_<lang>/' containing the macro name & string combinations.
275
276 :param intl_dir_path: Path to the intl directory.
277 :param core_name: Name of the core, used for the files' paths.
278 :param keyword_string_dict: Dictionary of the form { '_<lang>': { 'macro': 'string', ... }, ... }.
279 :return: Dictionary of the form { '_<lang>': 'path/to/file (./intl/_<lang>/<core_name>.h)', ... }.
280 """
281 files = {}
282 for localisation in keyword_string_dict:
283 path = os.path.join(intl_dir_path, core_name) # intl/<core_name>/
284 files[localisation] = os.path.join(path, localisation + '.h') # intl/<core_name>/_<lang>.h
285 if not os.path.exists(path):
286 os.makedirs(path)
287 with open(files[localisation], 'w', encoding='utf-8') as crowdin_file:
288 out_text = ''
289 for keyword in keyword_string_dict[localisation]:
290 out_text = f'{out_text}{keyword} {keyword_string_dict[localisation][keyword]}\n'
291 crowdin_file.write(out_text)
292 return files
293
294
295 def h2json(file_paths: dict) -> dict:
296 """Converts .h files pointed to by file_paths into .jsons.
297
298 :param file_paths: Dictionary of the form { '_<lang>': 'path/to/file (./intl/_<lang>/<core_name>.h)', ... }.
299 :return: Dictionary of the form { '_<lang>': 'path/to/file (./intl/_<lang>/<core_name>.json)', ... }.
300 """
301 jsons = {}
302 for file_lang in file_paths:
303 if not os.path.isfile(file_paths[file_lang]):
304 continue
305 file_path = file_paths[file_lang]
306 try:
307 jsons[file_lang] = file_path[:file_path.rindex('.')] + '.json'
308 except ValueError:
309 print(f"File {file_path} has incorrect format! File ending missing?")
310 continue
311
312 p = cor.p_masked
313
314 with open(file_paths[file_lang], 'r+', encoding='utf-8') as h_file:
315 text = h_file.read()
316 result = p.finditer(text)
317 messages = {}
318 for msg in result:
319 key, val = msg.group(1, 2)
320 if key not in messages:
321 if key and val:
322 # unescape & remove "\n"
323 messages[key] = re.sub(r'"\s*(?:(?:/\*(?:.|[\r\n])*?\*/|//.*[\r\n]+)\s*)*"',
324 '\\\n', val[1:-1].replace('\\\"', '"'))
325 else:
326 print(f"DUPLICATE KEY in {file_paths[file_lang]}: {key}")
327 with open(jsons[file_lang], 'w', encoding='utf-8') as json_file:
328 json.dump(messages, json_file, indent=2)
329
330 return jsons
331
332
333 def json2h(intl_dir_path: str, file_list) -> None:
334 """Converts .json file in json_file_path into an .h ready to be included in C code.
335
336 :param intl_dir_path: Path to the intl/<core_name> directory.
337 :param file_list: Iterator of os.DirEntry objects. Contains localisation files to convert.
338 :return: None
339 """
340
341 p = cor.p_masked
342
343 def update(s_messages, s_template, s_source_messages, file_name):
344 translation = ''
345 template_messages = p.finditer(s_template)
346 for tp_msg in template_messages:
347 old_key = tp_msg.group(1)
348 if old_key in s_messages and s_messages[old_key] != s_source_messages[old_key]:
349 tl_msg_val = s_messages[old_key]
350 tl_msg_val = tl_msg_val.replace('"', '\\\"').replace('\n', '') # escape
351 translation = ''.join((translation, '#define ', old_key, file_name.upper(), f' "{tl_msg_val}"\n'))
352
353 else: # Remove English duplicates and non-translatable strings
354 translation = ''.join((translation, '#define ', old_key, file_name.upper(), ' NULL\n'))
355 return translation
356
357 us_h = os.path.join(intl_dir_path, '_us.h')
358 us_json = os.path.join(intl_dir_path, '_us.json')
359
360 with open(us_h, 'r', encoding='utf-8') as template_file:
361 template = template_file.read()
362 with open(us_json, 'r+', encoding='utf-8') as source_json_file:
363 source_messages = json.load(source_json_file)
364
365 for file in file_list:
366 if file.name.lower().startswith('_us') \
367 or file.name.lower().endswith('.h') \
368 or file.is_dir():
369 continue
370
371 with open(file.path, 'r+', encoding='utf-8') as json_file:
372 messages = json.load(json_file)
373 new_translation = update(messages, template, source_messages, os.path.splitext(file.name)[0])
374 with open(os.path.splitext(file.path)[0] + '.h', 'w', encoding='utf-8') as h_file:
375 h_file.seek(0)
376 h_file.write(new_translation)
377 h_file.truncate()
378 return
379
380
381 def get_crowdin_client(dir_path: str) -> str:
382 """Makes sure the Crowdin CLI client is present. If it isn't, it is fetched & extracted.
383
384 :return: The path to 'crowdin-cli.jar'.
385 """
386 jar_name = 'crowdin-cli.jar'
387 jar_path = os.path.join(dir_path, jar_name)
388
389 if not os.path.isfile(jar_path):
390 print('Downloading crowdin-cli.jar')
391 crowdin_cli_file = os.path.join(dir_path, 'crowdin-cli.zip')
392 crowdin_cli_url = 'https://downloads.crowdin.com/cli/v3/crowdin-cli.zip'
393 req.urlretrieve(crowdin_cli_url, crowdin_cli_file)
394 import zipfile
395 with zipfile.ZipFile(crowdin_cli_file, 'r') as zip_ref:
396 jar_dir = zip_ref.namelist()[0]
397 for file in zip_ref.namelist():
398 if file.endswith(jar_name):
399 jar_file = file
400 break
401 zip_ref.extract(jar_file)
402 os.rename(jar_file, jar_path)
403 os.remove(crowdin_cli_file)
404 shutil.rmtree(jar_dir)
405 return jar_path
406
407
408 def create_intl_file(intl_file_path: str, localisations_path: str, text: str, file_path: str) -> None:
409 """Creates 'libretro_core_options_intl.h' from Crowdin translations.
410
411 :param intl_file_path: Path to 'libretro_core_options_intl.h'
412 :param localisations_path: Path to the intl/<core_name> directory.
413 :param text: Content of the 'libretro_core_options.h' being translated.
414 :param file_path: Path to the '_us.h' file, containing the original English texts.
415 :return: None
416 """
417 msg_dict = {}
418 lang_up = ''
419
420 def replace_pair(pair_match):
421 """Replaces a key-value-pair of an option with the macros corresponding to the language.
422
423 :param pair_match: The re match object representing the key-value-pair block.
424 :return: Replacement string.
425 """
426 offset = pair_match.start(0)
427 if pair_match.group(1): # key
428 if pair_match.group(2) in msg_dict: # value
429 val = msg_dict[pair_match.group(2)] + lang_up
430 elif pair_match.group(1) in msg_dict: # use key if value not viable (e.g. NULL)
431 val = msg_dict[pair_match.group(1)] + lang_up
432 else:
433 return pair_match.group(0)
434 else:
435 return pair_match.group(0)
436 res = pair_match.group(0)[:pair_match.start(2) - offset] + val \
437 + pair_match.group(0)[pair_match.end(2) - offset:]
438 return res
439
440 def replace_info(info_match):
441 """Replaces the 'additional strings' of an option with the macros corresponding to the language.
442
443 :param info_match: The re match object representing the 'additional strings' block.
444 :return: Replacement string.
445 """
446 offset = info_match.start(0)
447 if info_match.group(1) in msg_dict:
448 res = info_match.group(0)[:info_match.start(1) - offset] + \
449 msg_dict[info_match.group(1)] + lang_up + \
450 info_match.group(0)[info_match.end(1) - offset:]
451 return res
452 else:
453 return info_match.group(0)
454
455 def replace_option(option_match):
456 """Replaces strings within an option
457 '{ "opt_key", "label", "additional strings", ..., { {"key", "value"}, ... }, ... }'
458 within a struct with the macros corresponding to the language:
459 '{ "opt_key", MACRO_LABEL, MACRO_STRINGS, ..., { {"key", MACRO_VALUE}, ... }, ... }'
460
461 :param option_match: The re match object representing the option.
462 :return: Replacement string.
463 """
464 # label
465 offset = option_match.start(0)
466 if option_match.group(2):
467 res = option_match.group(0)[:option_match.start(2) - offset] + msg_dict[option_match.group(2)] + lang_up
468 else:
469 return option_match.group(0)
470 # additional block
471 if option_match.group(3):
472 res = res + option_match.group(0)[option_match.end(2) - offset:option_match.start(3) - offset]
473 new_info = p.sub(replace_info, option_match.group(3))
474 res = res + new_info
475 else:
476 return res + option_match.group(0)[option_match.end(2) - offset:]
477 # key-value-pairs
478 if option_match.group(4):
479 res = res + option_match.group(0)[option_match.end(3) - offset:option_match.start(4) - offset]
480 new_pairs = cor.p_key_value.sub(replace_pair, option_match.group(4))
481 res = res + new_pairs + option_match.group(0)[option_match.end(4) - offset:]
482 else:
483 res = res + option_match.group(0)[option_match.end(3) - offset:]
484
485 return res
486
487 # ------------------------------------------------------------------------------------
488
489 with open(file_path, 'r+', encoding='utf-8') as template: # intl/<core_name>/_us.h
490 masked_msgs = cor.p_masked.finditer(template.read())
491
492 for msg in masked_msgs:
493 msg_dict[msg.group(2)] = msg.group(1)
494
495 # top of the file - in case there is no file to copy it from
496 out_txt = "#ifndef LIBRETRO_CORE_OPTIONS_INTL_H__\n" \
497 "#define LIBRETRO_CORE_OPTIONS_INTL_H__\n\n" \
498 "#if defined(_MSC_VER) && (_MSC_VER >= 1500 && _MSC_VER < 1900)\n" \
499 "/* https://support.microsoft.com/en-us/kb/980263 */\n" \
500 '#pragma execution_character_set("utf-8")\n' \
501 "#pragma warning(disable:4566)\n" \
502 "#endif\n\n" \
503 "#include <libretro.h>\n\n" \
504 '#ifdef __cplusplus\n' \
505 'extern "C" {\n' \
506 '#endif\n'
507
508 if os.path.isfile(intl_file_path):
509 # copy top of the file for re-use
510 with open(intl_file_path, 'r', encoding='utf-8') as intl: # libretro_core_options_intl.h
511 in_text = intl.read()
512 # attempt 1: find the distinct comment header
513 intl_start = re.search(re.escape('/*\n'
514 ' ********************************\n'
515 ' * Core Option Definitions\n'
516 ' ********************************\n'
517 '*/\n'), in_text)
518 if intl_start:
519 out_txt = in_text[:intl_start.end(0)]
520 else:
521 # attempt 2: if no comment header present, find c++ compiler instruction (it is kind of a must)
522 intl_start = re.search(re.escape('#ifdef __cplusplus\n'
523 'extern "C" {\n'
524 '#endif\n'), in_text)
525 if intl_start:
526 out_txt = in_text[:intl_start.end(0)]
527 # if all attempts fail, use default from above
528
529 # only write to file, if there is anything worthwhile to write!
530 overwrite = False
531
532 # iterate through localisation files
533 files = {}
534 for file in os.scandir(localisations_path):
535 files[file.name] = {'is_file': file.is_file(), 'path': file.path}
536
537 for file in sorted(files): # intl/<core_name>/_*
538 if files[file]['is_file'] \
539 and file.startswith('_') \
540 and file.endswith('.h') \
541 and not file.startswith('_us'):
542 translation_path = files[file]['path'] # <core_name>_<lang>.h
543 # all structs: group(0) full struct, group(1) beginning, group(2) content
544 struct_groups = cor.p_struct.finditer(text)
545 lang_low = os.path.splitext(file)[0].lower()
546 lang_up = lang_low.upper()
547 # mark each language's section with a comment, for readability
548 out_txt = out_txt + f'/* RETRO_LANGUAGE{lang_up} */\n\n' # /* RETRO_LANGUAGE_NM */
549
550 # copy adjusted translations (makros)
551 with open(translation_path, 'r+', encoding='utf-8') as f_in: # <core name>.h
552 out_txt = out_txt + f_in.read() + '\n'
553 # replace English texts with makros
554 for construct in struct_groups:
555 declaration = construct.group(1)
556 struct_type_name = get_struct_type_name(declaration)
557 if 3 > len(struct_type_name): # no language specifier
558 new_decl = re.sub(re.escape(struct_type_name[1]), struct_type_name[1] + lang_low, declaration)
559 else:
560 if '_us' != struct_type_name[2]:
561 # only use _us constructs - other languages present in the source file are not important
562 continue
563 new_decl = re.sub(re.escape(struct_type_name[2]), lang_low, declaration)
564
565 p = (cor.p_info_cat if 'retro_core_option_v2_category' == struct_type_name[0] else cor.p_info)
566 offset_construct = construct.start(0)
567 # append localised construct name and ' = {'
568 start = construct.end(1) - offset_construct
569 end = construct.start(4) - offset_construct
570 out_txt = out_txt + new_decl + construct.group(0)[start:end]
571 # insert macros
572 content = construct.group(4)
573 new_content = cor.p_option.sub(replace_option, content)
574 start = construct.end(4) - offset_construct
575 # append macro-filled content and close the construct
576 out_txt = out_txt + new_content + construct.group(0)[start:] + '\n'
577
578 # for v2
579 if 'retro_core_option_v2_definition' == struct_type_name[0]:
580 out_txt = out_txt + f'struct retro_core_options_v2 options{lang_low}' \
581 ' = {\n' \
582 f' option_cats{lang_low},\n' \
583 f' option_defs{lang_low}\n' \
584 '};\n\n'
585 # if it got this far, we've got something to write
586 overwrite = True
587
588 # only write to file, if there is anything worthwhile to write!
589 if overwrite:
590 with open(intl_file_path, 'w', encoding='utf-8') as intl:
591 intl.write(out_txt + '\n#ifdef __cplusplus\n'
592 '}\n#endif\n'
593 '\n#endif')
594 return
595
596
597 # -------------------- MAIN -------------------- #
598
599 if __name__ == '__main__':
600 try:
601 if os.path.isfile(sys.argv[1]) or sys.argv[1].endswith('.h'):
602 _temp = os.path.dirname(sys.argv[1])
603 else:
604 _temp = sys.argv[1]
605 while _temp.endswith('/') or _temp.endswith('\\'):
606 _temp = _temp[:-1]
607 TARGET_DIR_PATH = _temp
608 except IndexError:
609 TARGET_DIR_PATH = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
610 print("No path provided, assuming parent directory:\n" + TARGET_DIR_PATH)
611
612 CORE_NAME = clean_file_name(sys.argv[2])
613
614 DIR_PATH = os.path.dirname(os.path.realpath(__file__))
615 H_FILE_PATH = os.path.join(TARGET_DIR_PATH, 'libretro_core_options.h')
616 INTL_FILE_PATH = os.path.join(TARGET_DIR_PATH, 'libretro_core_options_intl.h')
617
618 print('Getting texts from libretro_core_options.h')
619 with open(H_FILE_PATH, 'r+', encoding='utf-8') as _h_file:
620 _main_text = _h_file.read()
621 _hash_n_str = get_texts(_main_text)
622 _files = create_msg_hash(DIR_PATH, CORE_NAME, _hash_n_str)
623 _source_jsons = h2json(_files)
624
625 print('Getting texts from libretro_core_options_intl.h')
626 if os.path.isfile(INTL_FILE_PATH):
627 with open(INTL_FILE_PATH, 'r+', encoding='utf-8') as _intl_file:
628 _intl_text = _intl_file.read()
629 _hash_n_str_intl = get_texts(_intl_text)
630 _intl_files = create_msg_hash(DIR_PATH, CORE_NAME, _hash_n_str_intl)
631 _intl_jsons = h2json(_intl_files)
632
633 print('\nAll done!')