make_i18n.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. # Embeds the translation tables in the executable.
  2. # Usage: python3 tools/make_i18n.py (from the repository root)
  3. # Reads every resources/i18n/<id>.txt and writes src/ui/i18n/<id>.h, src/ui/i18n/_keys.h and src/ui/I18nData.h (the list).
  4. # Every table has the same English keys, so they are stored once (round 190sh: 4.97 MB of zlib data in every binary,
  5. # the app and each of the plugin pack's 23 plugin files, became 2.70 MB): _keys.h holds every key once ("..." with its
  6. # quotes, one per line, zlib-compressed); a table's header holds its .txt file with each line `"key" = "value"` written
  7. # as \x01"value" (the key after the previous line's) or \x02<key number> "value", zlib-compressed. Every other line is
  8. # kept as it is. lynx::i18n::unpackTable (ui/I18nTables.h) gives back the .txt file byte for byte when a language is
  9. # chosen; this script checks that before it writes anything, and the test translations_embedded_table_is_up_to_date
  10. # checks it against resources/i18n.
  11. import pathlib, re, zlib
  12. root = pathlib.Path(__file__).resolve().parent.parent
  13. # fixed order: the order of the Language menu is set in src/ui/I18n.cpp, this one only names the arrays
  14. ids = sorted(p.stem for p in (root / "resources/i18n").glob("*.txt"))
  15. texts = {lang: (root / f"resources/i18n/{lang}.txt").read_bytes() for lang in ids}
  16. # a line that is one string of the table: "key" = "value", both quoted with the format's escapes (\n \t \" \\)
  17. pair = re.compile(rb'^("(?:[^"\\]|\\.)*") = ("(?:[^"\\]|\\.)*")$')
  18. for lang, text in texts.items():
  19. if re.search(rb"[\x00-\x08]", text):
  20. raise SystemExit(f"resources/i18n/{lang}.txt holds a control byte below tab: not a text table")
  21. # the keys, once: pt-BR's order (the reference table), then any key only another table has, in file order
  22. keys, number = [], {}
  23. for lang in (["pt-BR"] if "pt-BR" in texts else []) + [i for i in ids if i != "pt-BR"]:
  24. for line in texts[lang].split(b"\n"):
  25. m = pair.match(line)
  26. if m and m.group(1) not in number:
  27. number[m.group(1)] = len(keys)
  28. keys.append(m.group(1))
  29. keys_text = b"\n".join(keys)
  30. def pack(text):
  31. out, previous = [], -1
  32. for line in text.split(b"\n"):
  33. m = pair.match(line)
  34. if m:
  35. k = number[m.group(1)]
  36. out.append((b"\x01" if k == previous + 1 else b"\x02" + str(k).encode() + b" ") + m.group(2))
  37. previous = k
  38. else:
  39. out.append(line)
  40. return b"\n".join(out)
  41. def unpack(packed): # (what ui/I18nTables.h does)
  42. out, previous = [], -1
  43. for line in packed.split(b"\n"):
  44. if line[:1] == b"\x01":
  45. previous += 1
  46. out.append(keys[previous] + b" = " + line[1:])
  47. elif line[:1] == b"\x02":
  48. space = line.index(b" ")
  49. previous = int(line[1:space])
  50. out.append(keys[previous] + b" = " + line[space + 1:])
  51. else:
  52. out.append(line)
  53. return b"\n".join(out)
  54. def array(name, data):
  55. lines = [f"inline constexpr unsigned char {name}[] = {{"]
  56. for i in range(0, len(data), 32):
  57. lines.append(",".join(str(b) for b in data[i:i + 32]) + ",")
  58. return lines + ["};"]
  59. packed = {}
  60. for lang in ids:
  61. body = pack(texts[lang])
  62. if unpack(body) != texts[lang]:
  63. raise SystemExit(f"resources/i18n/{lang}.txt does not come back byte for byte: not written")
  64. packed[lang] = (zlib.compress(body, 9), len(body))
  65. keys_zlib = zlib.compress(keys_text, 9)
  66. out = ["#pragma once", "",
  67. "// Generated by tools/make_i18n.py from resources/i18n/*.txt - do not edit by hand.",
  68. "// The tables are unpacked by lynx::i18n::unpackTable (ui/I18nTables.h).", "",
  69. "#include <cstddef>", "",
  70. "namespace lynx::i18n::data", "{",
  71. "struct Table",
  72. "{",
  73. " const char* id; // \"pt-BR\"",
  74. " const unsigned char* zlib; // the .txt file without its keys (tools/make_i18n.py), zlib-compressed",
  75. " std::size_t zlibSize, packedSize, textSize; // compressed / unpacked / the .txt file's size in bytes",
  76. "};", "} // namespace lynx::i18n::data", ""]
  77. names = []
  78. folder = root / "src/ui/i18n"
  79. folder.mkdir(exist_ok=True)
  80. for stale in folder.glob("*.h"):
  81. if stale.stem not in ids and stale.name != "_keys.h":
  82. stale.unlink()
  83. (folder / "_keys.h").write_text("\n".join(
  84. ["#pragma once", "",
  85. f"// Generated by tools/make_i18n.py from resources/i18n/*.txt: the tables' {len(keys)} keys, one per line "
  86. f"({len(keys_text)} bytes, zlib) - do not edit by hand.",
  87. "", "namespace lynx::i18n::data", "{"] + array("t_keys", keys_zlib) + ["} // namespace lynx::i18n::data", ""]))
  88. out.append('#include "ui/i18n/_keys.h"')
  89. for lang in ids:
  90. data, size = packed[lang]
  91. name = "t_" + lang.replace("-", "_")
  92. names.append((lang, name, len(data), size, len(texts[lang])))
  93. part = ["#pragma once", "",
  94. f"// Generated by tools/make_i18n.py from resources/i18n/{lang}.txt ({len(texts[lang])} bytes; without its keys, "
  95. "zlib) - do not edit by hand.",
  96. "", "namespace lynx::i18n::data", "{"] + array(name, data) + ["} // namespace lynx::i18n::data", ""]
  97. (folder / f"{lang}.h").write_text("\n".join(part))
  98. out.append(f'#include "ui/i18n/{lang}.h"')
  99. out += ["", "namespace lynx::i18n::data", "{",
  100. f"inline constexpr std::size_t keysZlibSize = {len(keys_zlib)}, keysTextSize = {len(keys_text)};",
  101. "inline constexpr Table tables[] = {"]
  102. for lang, name, n, size, text_size in names:
  103. out.append(f' {{ "{lang}", {name}, {n}, {size}, {text_size} }},')
  104. out.append("};")
  105. out.append("} // namespace lynx::i18n::data")
  106. out.append("")
  107. (root / "src/ui/I18nData.h").write_text("\n".join(out))
  108. total = len(keys_zlib) + sum(len(d) for d, _ in packed.values())
  109. print(f"{len(names)} table(s) -> src/ui/i18n/*.h + src/ui/I18nData.h ({len(keys)} keys; {total} bytes of zlib data)")
  110. # The English display table (rollup 0.1.31 step 3): resources/i18n/en/display.txt, a few lines that change what English
  111. # shows without changing the tr() keys every table is keyed by; small, so embedded as plain text in src/ui/I18nEnglish.h
  112. en = (root / "resources/i18n/en/display.txt").read_text(encoding="utf-8")
  113. body = "".join("\\%03o" % b if b >= 0x80 or b in (0x22, 0x5c) else chr(b) if b >= 0x20 else ("\\n\"\n \"" if b == 0x0a else "\\%03o" % b)
  114. for b in en.encode("utf-8"))
  115. (root / "src/ui/I18nEnglish.h").write_text("\n".join([
  116. "#pragma once", "",
  117. "// Generated by tools/make_i18n.py from resources/i18n/en/display.txt - do not edit by hand.", "",
  118. "namespace lynx::i18n::data", "{",
  119. "// what English shows for a few tr() keys (JUCE LocalisedStrings text)",
  120. "inline constexpr const char* englishDisplay =",
  121. " \"" + body + "\";",
  122. "} // namespace lynx::i18n::data", ""]))
  123. print("English display table -> src/ui/I18nEnglish.h")