1#!/usr/bin/python
2# Copyright (c) 2012-2016 The Bitcoin Core developers
3# Distributed under the MIT software license, see the accompanying
4# file COPYING or http://www.opensource.org/licenses/mit-license.php.
5'''
6Extract _("...") strings for translation and convert to Qt stringdefs so that
7they can be picked up by Qt linguist.
8'''
9from __future__ import division,print_function,unicode_literals
10from subprocess import Popen, PIPE
11import glob
12import operator
13import os
14import sys
15
16OUT_CPP="qt/bitcoinstrings.cpp"
17EMPTY=['""']
18
19def parse_po(text):
20    """
21    Parse 'po' format produced by xgettext.
22    Return a list of (msgid,msgstr) tuples.
23    """
24    messages = []
25    msgid = []
26    msgstr = []
27    in_msgid = False
28    in_msgstr = False
29
30    for line in text.split('\n'):
31        line = line.rstrip('\r')
32        if line.startswith('msgid '):
33            if in_msgstr:
34                messages.append((msgid, msgstr))
35                in_msgstr = False
36            # message start
37            in_msgid = True
38
39            msgid = [line[6:]]
40        elif line.startswith('msgstr '):
41            in_msgid = False
42            in_msgstr = True
43            msgstr = [line[7:]]
44        elif line.startswith('"'):
45            if in_msgid:
46                msgid.append(line)
47            if in_msgstr:
48                msgstr.append(line)
49
50    if in_msgstr:
51        messages.append((msgid, msgstr))
52
53    return messages
54
55files = sys.argv[1:]
56
57# xgettext -n --keyword=_ $FILES
58XGETTEXT=os.getenv('XGETTEXT', 'xgettext')
59if not XGETTEXT:
60    print('Cannot extract strings: xgettext utility is not installed or not configured.',file=sys.stderr)
61    print('Please install package "gettext" and re-run \'./configure\'.',file=sys.stderr)
62    exit(1)
63child = Popen([XGETTEXT,'--output=-','-n','--keyword=_'] + files, stdout=PIPE)
64(out, err) = child.communicate()
65
66messages = parse_po(out.decode('utf-8'))
67
68f = open(OUT_CPP, 'w')
69f.write("""
70
71#include <QtGlobal>
72
73// Automatically generated by extract_strings_qt.py
74#ifdef __GNUC__
75#define UNUSED __attribute__((unused))
76#else
77#define UNUSED
78#endif
79""")
80f.write('static const char UNUSED *bitcoin_strings[] = {\n')
81f.write('QT_TRANSLATE_NOOP("bitcoin-core", "%s"),\n' % (os.getenv('PACKAGE_NAME'),))
82f.write('QT_TRANSLATE_NOOP("bitcoin-core", "%s"),\n' % (os.getenv('COPYRIGHT_HOLDERS'),))
83if os.getenv('COPYRIGHT_HOLDERS_SUBSTITUTION') != os.getenv('PACKAGE_NAME'):
84    f.write('QT_TRANSLATE_NOOP("bitcoin-core", "%s"),\n' % (os.getenv('COPYRIGHT_HOLDERS_SUBSTITUTION'),))
85messages.sort(key=operator.itemgetter(0))
86for (msgid, msgstr) in messages:
87    if msgid != EMPTY:
88        f.write('QT_TRANSLATE_NOOP("bitcoin-core", %s),\n' % ('\n'.join(msgid)))
89f.write('};\n')
90f.close()
91