Menu entries, the SDDM theme and polkit policies are read by programs that know nothing of the FWS catalogs: every language is written into them at build time, and each program picks its user's language.
148 lines
6.0 KiB
Python
148 lines
6.0 KiB
Python
#!/usr/bin/env python3
|
|
"""Write the FWS translations into the files that cannot look them up.
|
|
|
|
Run at build time by customize_airootfs.sh (usage: translate-static-files.py
|
|
[--root DIR], DIR defaulting to /). Menu entries, the SDDM theme and polkit
|
|
policies are read by programs that know nothing of the FWS catalogs, so the
|
|
texts of system-translations.toml are written into them, every language at
|
|
once; each program then picks the language of its user.
|
|
|
|
- Desktop entries carrying X-FWS-Translation=<prefix> get their Name,
|
|
GenericName, Comment and Keywords from <prefix>.name, .generic_name,
|
|
.comment and .keywords: the English text as the plain key, the other
|
|
languages as Name[de]= and so on.
|
|
- The SDDM theme "fws" gets translations.js with every sddm.* text.
|
|
- A polkit action containing <!-- fws-i18n: <prefix> --> gets its
|
|
<description> and <message> from <prefix>.description and .message.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
from xml.sax.saxutils import escape
|
|
|
|
FWS_LIB = "/usr/local/lib/fws"
|
|
DESKTOP_DIRS = ["usr/share/applications", "etc/xdg/autostart", "usr/local/share/applications"]
|
|
DESKTOP_FIELDS = {"Name": "name", "GenericName": "generic_name",
|
|
"Comment": "comment", "Keywords": "keywords"}
|
|
SDDM_TRANSLATIONS = "usr/share/sddm/themes/fws/translations.js"
|
|
POLKIT_DIR = "usr/share/polkit-1/actions"
|
|
POLKIT_MARKER = re.compile(r"<!--\s*fws-i18n:\s*([a-z0-9_.]+)\s*-->")
|
|
|
|
|
|
def desktop_value(text, field):
|
|
text = text.replace("\\", "\\\\").replace("\n", "\\n").replace("\t", "\\t")
|
|
if field == "Keywords" and not text.endswith(";"):
|
|
text += ";"
|
|
return text
|
|
|
|
|
|
def translate_desktop_entry(path, messages):
|
|
with open(path, encoding="utf-8") as fh:
|
|
lines = fh.read().splitlines()
|
|
prefix = next((line.split("=", 1)[1].strip() for line in lines
|
|
if line.startswith("X-FWS-Translation=")), None)
|
|
if not prefix:
|
|
return False
|
|
out, group = [], None
|
|
for line in lines:
|
|
if line.startswith("["):
|
|
group = line.strip()
|
|
field = line.split("=", 1)[0]
|
|
base = field.split("[", 1)[0]
|
|
texts = messages.get(f"{prefix}.{DESKTOP_FIELDS.get(base, '')}")
|
|
if group != "[Desktop Entry]" or base not in DESKTOP_FIELDS or not texts:
|
|
out.append(line)
|
|
continue
|
|
if field != base:
|
|
continue # an old translation, rewritten below
|
|
out.append(f"{base}={desktop_value(texts['en'], base)}")
|
|
for language in sorted(texts):
|
|
if language != "en":
|
|
out.append(f"{base}[{language}]={desktop_value(texts[language], base)}")
|
|
with open(path, "w", encoding="utf-8") as fh:
|
|
fh.write("\n".join(out) + "\n")
|
|
return True
|
|
|
|
|
|
def write_sddm_translations(path, messages):
|
|
sddm = {key: texts for key, texts in messages.items() if key.startswith("sddm.")}
|
|
with open(path, "w", encoding="utf-8") as fh:
|
|
fh.write(".pragma library\n"
|
|
"// Generated at build time from system-translations.toml.\n"
|
|
f"var messages = {json.dumps(sddm, ensure_ascii=False, sort_keys=True)};\n")
|
|
|
|
|
|
def translate_policy(path, messages):
|
|
with open(path, encoding="utf-8") as fh:
|
|
content = fh.read()
|
|
changed = False
|
|
|
|
def action(match):
|
|
nonlocal changed
|
|
block = match.group(0)
|
|
marker = POLKIT_MARKER.search(block)
|
|
if not marker:
|
|
return block
|
|
for element in ("description", "message"):
|
|
texts = messages.get(f"{marker.group(1)}.{element}")
|
|
if not texts:
|
|
continue
|
|
# Drop earlier translations, then put the English text back with
|
|
# every other language after it.
|
|
block = re.sub(rf"\s*<{element} xml:lang=\"[^\"]*\">.*?</{element}>", "", block)
|
|
base = re.search(rf"([ \t]*)<{element}>.*?</{element}>", block)
|
|
if not base:
|
|
continue
|
|
indent = base.group(1)
|
|
lines = [f"{indent}<{element}>{escape(texts['en'])}</{element}>"]
|
|
lines += [f"{indent}<{element} xml:lang=\"{language}\">{escape(text)}</{element}>"
|
|
for language, text in sorted(texts.items()) if language != "en"]
|
|
block = block[:base.start()] + "\n".join(lines) + block[base.end():]
|
|
changed = True
|
|
return block
|
|
|
|
content = re.sub(r"<action\b.*?</action>", action, content, flags=re.S)
|
|
if changed:
|
|
with open(path, "w", encoding="utf-8") as fh:
|
|
fh.write(content)
|
|
return changed
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
|
parser.add_argument("--root", default="/")
|
|
args = parser.parse_args()
|
|
|
|
sys.path.insert(0, os.path.join(args.root, FWS_LIB.lstrip("/")))
|
|
import fws_i18n # pylint: disable=import-outside-toplevel
|
|
fws_i18n.TRANSLATIONS_DIR = os.path.join(args.root, fws_i18n.TRANSLATIONS_DIR.lstrip("/"))
|
|
messages = fws_i18n.catalog("system").messages()
|
|
if not messages:
|
|
print("translate-static-files: system-translations.toml missing or unreadable",
|
|
file=sys.stderr)
|
|
return 1
|
|
|
|
done = []
|
|
for folder in DESKTOP_DIRS:
|
|
folder = os.path.join(args.root, folder)
|
|
for name in sorted(os.listdir(folder)) if os.path.isdir(folder) else []:
|
|
if name.endswith(".desktop") and translate_desktop_entry(os.path.join(folder, name), messages):
|
|
done.append(name)
|
|
sddm = os.path.join(args.root, SDDM_TRANSLATIONS)
|
|
if os.path.isdir(os.path.dirname(sddm)):
|
|
write_sddm_translations(sddm, messages)
|
|
done.append("sddm")
|
|
policies = os.path.join(args.root, POLKIT_DIR)
|
|
for name in sorted(os.listdir(policies)) if os.path.isdir(policies) else []:
|
|
if name.startswith("org.fws.") and translate_policy(os.path.join(policies, name), messages):
|
|
done.append(name)
|
|
print(f"translate-static-files: {', '.join(done) or 'nothing to translate'}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|