# This file is part of Beremiz
# Copyright (C) 2021: Edouard TISSERANT
# See COPYING file for copyrights details.
from email.parser import HeaderParser
from dialogs import MessageBoxOnce
from POULibrary import UserAddressedException
cmd_parser = re.compile(r'(?:"([^"]+)"\s*|([^\s]+)\s*)?')
""" Opens PO file with POEdit """
if sys.platform.startswith('win'):
poedit_cmd = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE,
'SOFTWARE\\Classes\\poedit\\shell\\open\\command')
cmd = re.findall(cmd_parser, poedit_cmd)
dblquote_value,smpl_value = cmd[0]
poedit_path = dblquote_value+smpl_value
MessageBoxOnce("Launching POEdit with xdg-open",
"Confined app can't launch POEdit directly.\n"+
"Instead, PO/POT file is passed to xdg-open.\n"+
"Please select POEdit when proposed.\n\n"+
" - POEdit must be installed on you system.\n"+
" - If no choice is proposed, use file manager to change POT/PO file properties.\n",
poedit_path = subprocess.check_output("command -v poedit", shell=True).strip()
except subprocess.CalledProcessError:
wx.MessageBox("POEdit is not found or installed !")
subprocess.Popen([poedit_path,pofile])
def EtreeToMessages(msgs):
""" Converts XML tree from 'extract_i18n' templates into a list of tuples """
b"\n".join([line.text.encode() for line in msg]),
msg.get("label").encode(), msg.get("id").encode()))
def SaveCatalog(fname, messages):
""" Save messages given as list of tupple (msg,label,id) in POT file """
w.ImportMessages(messages)
with open(fname, 'wb') as POT_file:
po_files = [fname for fname in os.listdir(dirpath) if fname.endswith(".po")]
return [(po_fname[:-3],os.path.join(dirpath, po_fname)) for po_fname in po_files]
def ReadTranslations(dirpath):
""" Read all PO files from a directory and return a list of (langcode, translation_dict) tuples """
for translation_name, po_path in GetPoFiles(dirpath):
messages = POReader().read(po_path)
translations.append((translation_name, messages))
def MatchTranslations(translations, messages, errcallback):
Matches translations against original message catalog,
warn about inconsistancies,
returns list of langs, and a list of (msgid, [translations]) tuples
for msgid,label,svgid in messages:
for langcode,translation in translations:
msg = translation.pop(msgid, None)
# Missing translation (msgid not in .po)
broken_lang.add(langcode)
# Empty translation (msgid is in .po)
incomplete_lang.add(langcode)
translated_message.append(msg)
translated_messages.append((msgid,translated_message))
for langcode,translation in translations:
l,c = langcode.split("_")
language_name = pycountry.languages.get(alpha_2 = l).name
country_name = pycountry.countries.get(alpha_2 = c).name
langname = "{} ({})".format(language_name, country_name)
langname = pycountry.languages.get(alpha_2 = langcode).name
langs.append((langname,langcode))
if broken or langcode in broken_lang:
_('Translation for {} is outdated and incomplete.')
if langcode in incomplete_lang else
_('Translation for {} is outdated.')).format(langcode) +
" "+_('Edit {}.po, click "Catalog -> Update from POT File..." and select messages.pot.\n').format(langcode))
elif langcode in incomplete_lang:
errcallback(_('Translation for {} is incomplete. Edit {}.po to complete it.\n').format(langcode,langcode))
return langs,translated_messages
def TranslationToEtree(langs,translated_messages):
result = etree.Element("translations")
langsroot = etree.SubElement(result, "langs")
langel = etree.SubElement(langsroot, "lang", {"code":code})
msgsroot = etree.SubElement(result, "messages")
for msgid, msgs in translated_messages:
msgidel = etree.SubElement(msgsroot, "msgid")
msgel = etree.SubElement(msgidel, "msg")
for line in msg.split(b"\n"):
lineel = etree.SubElement(msgel, "line")
lineel.text = escape(line).decode()
# Code below is based on :
# cpython/Tools/i18n/pygettext.py
# cpython/Tools/i18n/msgfmt.py
locpfx = b'#:svghmi.svg:'
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR ORGANIZATION
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
"Project-Id-Version: PACKAGE VERSION\\n"
"POT-Creation-Date: %(time)s\\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\\n"
"Language-Team: LANGUAGE <LL@li.org>\\n"
"Content-Type: text/plain; charset=UTF-8\\n"
"Content-Transfer-Encoding: 8bit\\n"
"Generated-By: SVGHMI 1.0\\n"
escapes = [b"\%03o" % i for i in range(128)]
escapes[ord('\\')] = b'\\\\'
escapes[ord('\t')] = b'\\t'
escapes[ord('\r')] = b'\\r'
escapes[ord('\n')] = b'\\n'
escapes[ord('\"')] = b'\\"'
return b''.join([escapes[c] if c < 128 else bytes([c]) for c in s])
# This converts the various Python string types into a format that is
# appropriate for .po files, namely much closer to C style.
s = b'"' + escape(s) + b'"'
lines[-1] = lines[-1] + b'\n'
for i in range(len(lines)):
lines[i] = escape(lines[i])
s = b'""\n"' + lineterm.join(lines) + b'"'
def ImportMessages(self, msgs):
for msg, label, svgid in msgs:
self.addentry(msg, label, svgid)
def addentry(self, msg, label, svgid):
self.__messages.setdefault(msg, set()).add(entry)
timestamp = time.strftime('%Y-%m-%d %H:%M%z')
header = pot_header % {'time': timestamp}
fp.write(header.encode())
for k, v in self.__messages.items():
reverse.setdefault(tuple(keys), []).append((k, v))
rkeys = sorted(reverse.keys())
d = {b'label': label, b'svgid': svgid}
s = b' %(label)s:%(svgid)s' % d
if len(locline) + len(s) <= 78:
fp.write(locline + b'\n')
if len(locline) > len(locpfx):
fp.write(locline + b'\n')
fp.write(b'msgid ' + normalize(k) + b'\n')
fp.write(b'msgstr ""\n\n')
def add(self, ctxt, msgid, msgstr, fuzzy):
"Add eventually empty translation to the dictionary."
self.__messages[msgid if ctxt is None else (b"%b\x04%b" % (ctxt, id))] = msgstr
with open(infile, 'rb') as f:
raise UserAddressedException(
'Cannot open PO translation file :%s' % str(e))
# Start off assuming Latin-1, so everything decodes without failure,
# until we know the exact encoding
# If we get a comment line after a msgstr, this is a new entry
if l[0] == '#' and section == STR:
self.add(msgctxt, msgid, msgstr, fuzzy)
if l[:2] == '#,' and 'fuzzy' in l:
# Now we are in a msgid or msgctxt section, output previous section
if l.startswith('msgctxt'):
self.add(msgctxt, msgid, msgstr, fuzzy)
elif l.startswith('msgid') and not l.startswith('msgid_plural'):
self.add(msgctxt, msgid, msgstr, fuzzy)
# See whether there is an encoding declaration
charset = p.parsestr(msgstr.decode(encoding)).get_content_charset()
# This is a message with plural forms
elif l.startswith('msgid_plural'):
raise UserAddressedException(
'msgid_plural not preceded by msgid on %s:%d' % (infile, lno))
msgid += b'\0' # separator of singular and plural
# Now we are in a msgstr section
elif l.startswith('msgstr'):
if l.startswith('msgstr['):
raise UserAddressedException(
'plural without msgid_plural on %s:%d' % (infile, lno))
msgstr += b'\0' # Separator of the various plural forms
raise UserAddressedException(
'indexed msgstr required for plural on %s:%d' % (infile, lno))
msgctxt += l.encode(encoding)
msgid += l.encode(encoding)
msgstr += l.encode(encoding)
raise UserAddressedException(
'Syntax error on %s:%d' % (infile, lno) + 'before:\n %s'%l)
self.add(msgctxt, msgid, msgstr, fuzzy)