File: extract_strings_from_xml.py

package info (click to toggle)
unknown-horizons 2019.1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 347,832 kB
  • sloc: python: 46,804; xml: 3,137; sql: 1,189; sh: 736; makefile: 40; perl: 35
file content (217 lines) | stat: -rwxr-xr-x 7,034 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/env python3

# ###################################################
# Copyright (C) 2008-2017 The Unknown Horizons Team
# team@unknown-horizons.org
# This file is part of Unknown Horizons.
#
# Unknown Horizons is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# ###################################################

###############################################################################
#
# == I18N DEV USE CASES: CHEATSHEET ==
#
# ** Refer to  development/create_pot.sh  for help with building or updating
#    the translation files for Unknown Horizons.
#
###############################################################################
#
# THIS SCRIPT IS A HELPER SCRIPT. DO NOT INVOKE MANUALLY!
#
###############################################################################

from __future__ import print_function
import os
import sys
from xml.dom import minidom


if len(sys.argv) != 2:
	print('Error: Provide a file to write strings to as argument. Exiting.')
	sys.exit(1)

header = u'''\
# Encoding: utf-8
# ###################################################
# Copyright (C) 2008-2017 The Unknown Horizons Team
# team@unknown-horizons.org
# This file is part of Unknown Horizons.
#
# Unknown Horizons is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# ###################################################

###############################################################################
#
# == I18N DEV USE CASES: CHEATSHEET ==
#
# ** Refer to  development/create_pot.sh  for help with building or updating
#    the translation files for Unknown Horizons.
#
###############################################################################
#
# WARNING: This file is generated automagically.
#          You need to update it to see changes to strings in-game.
#          DO NOT MANUALLY UPDATE THIS FILE (by editing strings).
#          The script to generate .pot templates calls the following:
# ./development/extract_strings_from_xml.py  horizons/gui/translations.py
#
# NOTE: In string-freeze mode (shortly before releases, usually
#       announced in a meeting), updates to this file must not happen
#       without permission of the responsible translation admin!
#
###############################################################################

from typing import Dict, Tuple

from horizons.constants import VERSION
from horizons.i18n import gettext as T

text_translations = {} # type: Dict[str, Dict[Tuple[str, str], str]]

def set_translations():
	global text_translations
	text_translations = {
'''

FOOTER = u'''
	}
'''

FILE = u'''
	{filename!r} : {{
{entries}		}},
'''

ENTRY = u'''\
		({widget!r:<31}, {attribute!r:<10}): {text},
'''

files_to_skip = [
	'credits.xml',
	'stringpreviewwidget.xml',
	'startup_error_popup.xml',
]


def print_n_no_name(n, text):
	print('\tWarning: ', end=' ')
	print('{} without name. Add unique name if desired: text="{}"'.format(n, text))


def list_all_files():
	result = []
	walker = os.walk('content/gui/xml')
	for root, dirs, files in walker:
		for filename in files:
			if filename.endswith('.xml'):
				result.append(('{}/{}'.format(root, filename), filename not in files_to_skip))
	return sorted(result)


def content_from_element(element_name, parse_tree, attribute):
	"""Extracts text content of one attribute from a widget in the DOM.

	element_name: name of widget
	parse_tree: xml tree to parse
	attribute: usually 'text' or 'helptext'
	"""
	default_names = {
		'OkButton': u'okButton',
		'CancelButton': u'cancelButton',
		'DeleteButton': u'deleteButton',
	}
	element_strings = []
	element_list = parse_tree.getElementsByTagName(element_name)

	for element in element_list:
		name = element.getAttribute('name')
		text = element.getAttribute(attribute)
		i18n = element.getAttribute('comment') # translator comment about widget context
		if i18n == 'noi18n':
			# comment='noi18n' in widgets where translation is not desired
			continue

		if i18n == 'noi18n_{}'.format(attribute):
			# comment='noi18n_tooltip' in widgets where tooltip translation is not
			# desired, but text should be translated.
			continue

		if not name:
			if element_name in default_names:
				name = default_names[element_name]
			elif text:
				print_n_no_name(element_name, text)

		if text and name:
			if name == 'version_label':
				text = 'VERSION.string()'
			else:
				text = 'T("{}")'.format(text)
			newline = ENTRY.format(attribute=attribute, widget=name, text=text)
			element_strings.append(newline)

	return ''.join(sorted(element_strings))


def content_from_file(filename, parse=True):
	"""Set parse=False if you want to list the widget in guitranslations,
	but not the strings. Usually because those strings are not reasonable
	to translate (credits, development widgets).
	"""
	def empty():
		return FILE.format(filename=printname, entries='')

	parsed = minidom.parse(filename)

	#HACK! we strip the string until no "/" occurs and then use the remaining part
	# this is necessary because of our dynamic widget loading (by unique file names)
	printname = filename.rsplit("/", 1)[1]
	if not parse:
		return empty()

	strings = ''
	for w in ['Button', 'CheckBox', 'Label', 'RadioButton']:
		strings += content_from_element(w, parsed, 'text')
	for w in ['CancelButton', 'DeleteButton', 'OkButton', 'Button', 'Icon', 'ImageButton', 'Label', 'ProgressBar']:
		strings += content_from_element(w, parsed, 'helptext')

	if not strings:
		return empty()

	return FILE.format(filename=printname, entries=strings)


filesnippets = (content_from_file(filename, parse) for (filename, parse) in list_all_files())
filesnippets = ''.join(content for content in filesnippets if content)

output = '{}{}{}'.format(header, filesnippets, FOOTER)

with open(sys.argv[1], 'w') as f:
	f.write(output)