| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- # Embeds the translation tables in the executable.
- # Usage: python3 tools/make_i18n.py (from the repository root)
- # 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).
- # Every table has the same English keys, so they are stored once (round 190sh: 4.97 MB of zlib data in every binary,
- # the app and each of the plugin pack's 23 plugin files, became 2.70 MB): _keys.h holds every key once ("..." with its
- # quotes, one per line, zlib-compressed); a table's header holds its .txt file with each line `"key" = "value"` written
- # as \x01"value" (the key after the previous line's) or \x02<key number> "value", zlib-compressed. Every other line is
- # kept as it is. lynx::i18n::unpackTable (ui/I18nTables.h) gives back the .txt file byte for byte when a language is
- # chosen; this script checks that before it writes anything, and the test translations_embedded_table_is_up_to_date
- # checks it against resources/i18n.
- import pathlib, re, zlib
- root = pathlib.Path(__file__).resolve().parent.parent
- # fixed order: the order of the Language menu is set in src/ui/I18n.cpp, this one only names the arrays
- ids = sorted(p.stem for p in (root / "resources/i18n").glob("*.txt"))
- texts = {lang: (root / f"resources/i18n/{lang}.txt").read_bytes() for lang in ids}
- # a line that is one string of the table: "key" = "value", both quoted with the format's escapes (\n \t \" \\)
- pair = re.compile(rb'^("(?:[^"\\]|\\.)*") = ("(?:[^"\\]|\\.)*")$')
- for lang, text in texts.items():
- if re.search(rb"[\x00-\x08]", text):
- raise SystemExit(f"resources/i18n/{lang}.txt holds a control byte below tab: not a text table")
- # the keys, once: pt-BR's order (the reference table), then any key only another table has, in file order
- keys, number = [], {}
- for lang in (["pt-BR"] if "pt-BR" in texts else []) + [i for i in ids if i != "pt-BR"]:
- for line in texts[lang].split(b"\n"):
- m = pair.match(line)
- if m and m.group(1) not in number:
- number[m.group(1)] = len(keys)
- keys.append(m.group(1))
- keys_text = b"\n".join(keys)
- def pack(text):
- out, previous = [], -1
- for line in text.split(b"\n"):
- m = pair.match(line)
- if m:
- k = number[m.group(1)]
- out.append((b"\x01" if k == previous + 1 else b"\x02" + str(k).encode() + b" ") + m.group(2))
- previous = k
- else:
- out.append(line)
- return b"\n".join(out)
- def unpack(packed): # (what ui/I18nTables.h does)
- out, previous = [], -1
- for line in packed.split(b"\n"):
- if line[:1] == b"\x01":
- previous += 1
- out.append(keys[previous] + b" = " + line[1:])
- elif line[:1] == b"\x02":
- space = line.index(b" ")
- previous = int(line[1:space])
- out.append(keys[previous] + b" = " + line[space + 1:])
- else:
- out.append(line)
- return b"\n".join(out)
- def array(name, data):
- lines = [f"inline constexpr unsigned char {name}[] = {{"]
- for i in range(0, len(data), 32):
- lines.append(",".join(str(b) for b in data[i:i + 32]) + ",")
- return lines + ["};"]
- packed = {}
- for lang in ids:
- body = pack(texts[lang])
- if unpack(body) != texts[lang]:
- raise SystemExit(f"resources/i18n/{lang}.txt does not come back byte for byte: not written")
- packed[lang] = (zlib.compress(body, 9), len(body))
- keys_zlib = zlib.compress(keys_text, 9)
- out = ["#pragma once", "",
- "// Generated by tools/make_i18n.py from resources/i18n/*.txt - do not edit by hand.",
- "// The tables are unpacked by lynx::i18n::unpackTable (ui/I18nTables.h).", "",
- "#include <cstddef>", "",
- "namespace lynx::i18n::data", "{",
- "struct Table",
- "{",
- " const char* id; // \"pt-BR\"",
- " const unsigned char* zlib; // the .txt file without its keys (tools/make_i18n.py), zlib-compressed",
- " std::size_t zlibSize, packedSize, textSize; // compressed / unpacked / the .txt file's size in bytes",
- "};", "} // namespace lynx::i18n::data", ""]
- names = []
- folder = root / "src/ui/i18n"
- folder.mkdir(exist_ok=True)
- for stale in folder.glob("*.h"):
- if stale.stem not in ids and stale.name != "_keys.h":
- stale.unlink()
- (folder / "_keys.h").write_text("\n".join(
- ["#pragma once", "",
- f"// Generated by tools/make_i18n.py from resources/i18n/*.txt: the tables' {len(keys)} keys, one per line "
- f"({len(keys_text)} bytes, zlib) - do not edit by hand.",
- "", "namespace lynx::i18n::data", "{"] + array("t_keys", keys_zlib) + ["} // namespace lynx::i18n::data", ""]))
- out.append('#include "ui/i18n/_keys.h"')
- for lang in ids:
- data, size = packed[lang]
- name = "t_" + lang.replace("-", "_")
- names.append((lang, name, len(data), size, len(texts[lang])))
- part = ["#pragma once", "",
- f"// Generated by tools/make_i18n.py from resources/i18n/{lang}.txt ({len(texts[lang])} bytes; without its keys, "
- "zlib) - do not edit by hand.",
- "", "namespace lynx::i18n::data", "{"] + array(name, data) + ["} // namespace lynx::i18n::data", ""]
- (folder / f"{lang}.h").write_text("\n".join(part))
- out.append(f'#include "ui/i18n/{lang}.h"')
- out += ["", "namespace lynx::i18n::data", "{",
- f"inline constexpr std::size_t keysZlibSize = {len(keys_zlib)}, keysTextSize = {len(keys_text)};",
- "inline constexpr Table tables[] = {"]
- for lang, name, n, size, text_size in names:
- out.append(f' {{ "{lang}", {name}, {n}, {size}, {text_size} }},')
- out.append("};")
- out.append("} // namespace lynx::i18n::data")
- out.append("")
- (root / "src/ui/I18nData.h").write_text("\n".join(out))
- total = len(keys_zlib) + sum(len(d) for d, _ in packed.values())
- print(f"{len(names)} table(s) -> src/ui/i18n/*.h + src/ui/I18nData.h ({len(keys)} keys; {total} bytes of zlib data)")
- # The English display table (rollup 0.1.31 step 3): resources/i18n/en/display.txt, a few lines that change what English
- # shows without changing the tr() keys every table is keyed by; small, so embedded as plain text in src/ui/I18nEnglish.h
- en = (root / "resources/i18n/en/display.txt").read_text(encoding="utf-8")
- 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)
- for b in en.encode("utf-8"))
- (root / "src/ui/I18nEnglish.h").write_text("\n".join([
- "#pragma once", "",
- "// Generated by tools/make_i18n.py from resources/i18n/en/display.txt - do not edit by hand.", "",
- "namespace lynx::i18n::data", "{",
- "// what English shows for a few tr() keys (JUCE LocalisedStrings text)",
- "inline constexpr const char* englishDisplay =",
- " \"" + body + "\";",
- "} // namespace lynx::i18n::data", ""]))
- print("English display table -> src/ui/I18nEnglish.h")
|