-
-
Notifications
You must be signed in to change notification settings - Fork 988
/
wmldata.py
executable file
·655 lines (537 loc) · 20 KB
/
wmldata.py
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
#!/usr/bin/env python2
# encoding: utf-8
"""
NOTE: You should use wmlparser2.py instead which uses the C++
preprocessor.
This module represents the internal appearance of WML.
Note: We cannot store textdomain information, due to how the parser work.
For example:
name = _"x" + {foor} + {bar}
That string may actually be composed from three different textdomains. The
textdomain stuff in here is therefore only useful to CampGen, as that does
not allow composed strings like above.
"""
from __future__ import print_function
import re, sys
import wmlparser
import codecs
class Data:
"""Common subclass."""
def __init__(self, name):
self.name = name
self.file = "(None)"
self.line = -1
def __str__( self ):
return self.debug(show_contents = True, write = False)
def debug(self, show_contents = False, use_color = False, indent=0, write=True):
if use_color:
magenta = "\x1b[35;1m"
off = "\x1b[0m"
else:
magenta = off = ""
pos = indent * " "
result = pos + "\ " + magenta + self.name + off + " (" + self.__class__.__name__ + ")"
if show_contents:
if self.is_translatable() == True:
result += " _"
result += " '" + self.get_value() + "'"
if write:
# The input usually is utf8, but it also may be not - for example
# if a .png image is transmitted over WML. As this is only for
# display purposes, we ask Python to replace any garbage - and then
# re-encode as utf8 for console output.
text = result.decode("utf8", "replace")
text = text.encode("utf8", "replace")
sys.stdout.write(text)
sys.stdout.write("\n")
else: return result
def copy(self):
c = self.__class__(self.name, self.data) # this makes a new instance or so I was told
return c
def compare(self, other):
return self.name == other.name and self.data == other.data
def get_value(self):
return ""
def is_translatable(self):
return False
def get_type(self):
return self.__class__.__name__
def set_meta(self, file, line):
self.file = file
self.line = line
def get_meta(self):
return (self.file, self.line,)
class DataText(Data):
"""Represents any text strings."""
def __init__(self, name, text, translatable = False):
Data.__init__(self, name)
self.data = text
self.translatable = translatable
def copy(self):
return DataText(self.name, self.data, self.translatable)
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
def is_translatable(self):
return self.translatable
class DataBinary(Data):
"""A binary chunk of WML."""
def __init__(self, name, binary):
Data.__init__(self, name)
self.data = binary
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataMacro(Data):
"""A macro."""
def __init__(self, name, macro):
Data.__init__(self, name)
self.data = macro
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataDefine(Data):
"""A definition."""
def __init__(self, name, params, define):
Data.__init__(self, name)
self.params = params
self.data = define
def copy(self):
return DataDefine(self.name, self.params, self.data)
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataComment(Data):
"""A comment (normally discarded)."""
def __init__(self, name, comment):
Data.__init__(self, name)
self.data = comment
def get_value(self):
return self.data
def set_value(self, data):
self.data = data
class DataClosingTag(Data):
"""Yes, those are kept."""
def __init__(self, name):
Data.__init__(self, name)
self.data = None
class WMLException(Exception):
def __init__(self, text):
super( WMLException, self ).__init__()
self.text = text
print(text)
def __str__(self):
return self.text
class DataSub(Data):
def __init__(self, name, sub = [], textdomain=None):
"""The sub parameter is a list of sub-elements."""
Data.__init__(self, name)
self.data = []
self.dict = {}
self.textdomain = textdomain
for element in sub:
self.insert(element)
def clean_empty_ifdefs(self):
rem = []
for item in self.data:
if isinstance(item, DataIfDef):
if item.data == []:
rem.append(item)
if isinstance(item, DataSub):
item.clean_empty_ifdefs()
while rem:
item = rem.pop()
print("Removing empty #ifdef %s" % item.name)
self.remove(item)
def write_file(self, f, indent=0, textdomain=""):
f.write(self.make_string( indent, textdomain))
def make_string(self, indent = 0, textdomain = ""):
"""Write the data object to the given file object."""
ifdef = 0
result = []
self.clean_empty_ifdefs()
for item in self.data:
if ifdef:
if not isinstance(item, DataIfDef) or not item.type == "else":
result.append("#endif\n")
ifdef = 0
if isinstance(item, DataIfDef):
if item.type == "else":
result.append("#else\n")
else:
result.append("#ifdef %s\n" % item.name)
result.append( item.make_string(indent + 4, textdomain) )
ifdef = 1
elif isinstance(item, DataSub):
result.append(" " * indent)
result.append("[%s]\n" % item.name)
result.append(item.make_string(indent + 4, textdomain))
result.append(" " * indent)
close = item.name
if close[0] == "+": close = close[1:]
result.append("[/%s]\n" % close)
elif isinstance(item, DataText):
result.append(" " * indent)
text = item.data.replace('"', r'""')
# We always enclosed in quotes
# In theory, the parser will just remove then on reading in, so
# the actual value is 1:1 preserved
# TODO: is there no catch?
if textdomain and item.textdomain == "wesnoth":
result.append("#textdomain wesnoth\n")
result.append(" " * indent)
# FIXME: don't compile regex's if they are one shots
if item.translatable:
if "=" in text:
text = re.compile("=(.*?)(?=[=;]|$)"
).sub("=\" + _\"\\1\" + \"", text)
text = '"' + text + '"'
text = re.compile(r'\+ _""').sub("", text)
result.append('%s=%s\n' % (item.name, text))
else:
result.append('%s=_"%s"\n' % (item.name, text))
else:
result.append('%s="%s"\n' % (item.name, text))
if textdomain and item.textdomain == "wesnoth":
result.append(" " * indent)
result.append("#textdomain %s\n" % textdomain)
elif isinstance(item, DataMacro):
result.append(" " * indent)
result.append("%s\n" % item.data)
elif isinstance(item, DataComment):
result.append("%s\n" % item.data)
elif isinstance(item, DataDefine):
result.append("#define %s %s\n%s#enddef\n" % (item.name, item.params,
item.data))
elif isinstance(item, DataClosingTag):
result.append("[/%s]\n" % item.name)
elif isinstance(item, DataBinary):
data = item.data.replace('"', r'""')
result.append("%s=\"%s\"\n" % (
item.name, data))
else:
raise WMLException("Unknown item: %s" % item.__class__.__name__)
if ifdef:
result.append("#endif\n")
bytes = ""
for r in result:
if r != None:
# For networking, we need actual bytestream here, not unicode.
if type(r) is unicode: r = r.encode("utf8")
bytes += str(r)
return bytes
def is_empty(self):
return len(self.data) == 0
def children(self):
return self.data
def place_dict(self, data):
if data.name in self.dict:
self.dict[data.name] += [data]
else:
self.dict[data.name] = [data]
def append(self, other):
"""Append all elements of other."""
for item in other.data:
self.insert(item)
def insert(self, data):
"""Inserts a sub-element."""
self.data += [data]
self.place_dict(data)
def insert_first(self, data):
self.data = [data] + self.data
if data.name in self.dict:
self.dict[data.name] = [data] + self.dict[data.name]
else:
self.dict[data.name] = [data]
def insert_after(self, previous, data):
"""Insert after given node, or else insert as first."""
if not previous in self.data: return self.insert_first(data)
# completely rebuild list and dict
new_childs = []
self.dict = {}
for child in self.data:
new_childs += [child]
self.place_dict(child)
if child == previous:
new_childs += [data]
self.place_dict(data)
self.data = new_childs
def insert_at(self, pos, data):
"""Insert at given index (or as last)."""
if pos >= len(self.data): return self.insert(data)
# completely rebuild list and dict
new_childs = []
self.dict = {}
i = 0
for child in self.data:
if i == pos:
new_childs += [data]
self.place_dict(data)
new_childs += [child]
self.place_dict(child)
i += 1
self.data = new_childs
def insert_as_nth(self, pos, data):
"""Insert as nth child of same name."""
if pos == 0: return self.insert_first(data)
already = self.get_all(data.name)
before = already[pos - 1]
self.insert_after(before, data)
def remove(self, child):
"""Removes a sub-element."""
self.data.remove(child)
self.dict[child.name].remove(child)
def clear(self):
"""Remove everything."""
self.data = []
self.dict = {}
def copy(self):
"""Return a recursive copy of the element."""
copy = DataSub(self.name)
for item in self.data:
subcopy = item.copy()
copy.insert(subcopy)
return copy
def compare(self, other):
if len(self.data) != len(other.data): return False
for i in xrange(self.data):
if not self.data[i].compare(other.data[i]): return False
return True
def rename_child(self, child, name):
self.dict[child.name].remove(child)
child.name = name
# rebuild complete mapping for this name
if name in self.dict: del self.dict[name]
for item in self.data:
if item.name == name:
if name in self.dict:
self.dict[name] += [item]
else:
self.dict[name] = [item]
def insert_text(self, name, data, translatable = False,
textdomain = ""):
data = DataText(name, data, translatable = translatable)
data.textdomain = textdomain
self.insert(data)
def insert_macro(self, name, args = None):
macrodata = "{" + name
if args: macrodata += " " + str(args)
macrodata += "}"
data = DataMacro(name, macrodata)
self.insert(data)
def get_first(self, name, default = None):
"""Return first of given tag, or default"""
if not name in self.dict or not self.dict[name]: return default
return self.dict[name][0]
def get_all_with_attributes(self, attr_name, **kw):
"""Like get_or_create_sub_with_attributes."""
ret = []
for data in self.get_all(attr_name):
if isinstance(data, DataSub):
for key in kw:
if data.get_text_val(key) != kw[key]:
break
else:
ret += [data]
return ret
def get_or_create_sub(self, name):
for data in self.get_all(name):
if isinstance(data, DataSub): return data
sub = DataSub(name, [])
self.insert(sub)
return sub
def create_sub(self, name):
sub = DataSub(name, [])
self.insert(sub)
return sub
def get_or_create_sub_with_attributes(self, name, **kw):
"""For the uber lazy. Example:
event = scenario.get_or_create_sub_with_attribute("event", name = "prestart")
That should find the first prestart event and return it, or else
create and insert a new prestart event and return it.
"""
for data in self.get_all(name):
if isinstance(data, DataSub):
for key in kw:
if data.get_text_val(key) != kw[key]:
break
else:
return data
sub = DataSub(name, [])
for key in kw:
sub.set_text_val(key, kw[key])
self.insert(sub)
return sub
def get_or_create_ifdef(self, name):
for data in self.get_all(name):
if isinstance(data, DataIfDef): return data
ifdef = DataIfDef(name, [], "then")
self.insert(ifdef)
return ifdef
def delete_all(self, name):
while 1:
data = self.get_first(name)
if not data: break
self.remove(data)
def remove_all(self, name):
self.delete_all(name)
def find_all(self, *args):
"""Return list of multiple tags"""
return [item for item in self.data if item.name in args]
def get_all(self, name):
"""Return a list of all sub-items matching the given name."""
if not name in self.dict: return []
return self.dict[name]
def get_text(self, name):
"""Return a text element"""
for data in self.get_all(name):
if isinstance(data, DataText): return data
return None
def get_texts(self, name):
"""Gets all text elements matching the name"""
return [text for text in self.get_all(name)
if isinstance(text, DataText)]
def get_all_text(self):
"""Gets all text elements"""
return [text for text in self.data
if isinstance(text, DataText)]
def get_binary(self, name):
"""Return a binary element"""
for data in self.get_all(name):
if isinstance(data, DataBinary): return data
return None
def remove_text(self, name):
text = self.get_text(name)
if text: self.remove(text)
def get_macros(self, name):
"""Gets all macros matching the name"""
return [macro for macro in self.get_all(name)
if isinstance(macro, DataMacro)]
def get_all_macros(self):
"""Gets all macros"""
return [macro for macro in self.data
if isinstance(macro, DataMacro)]
def get_ifdefs(self, name):
"""Gets all ifdefs matching the name"""
return [ifdef for ifdef in self.get_all(name)
if isinstance(ifdef, DataIfDef)]
def get_subs(self, name):
"""Gets all elements matching the name"""
return [sub for sub in self.get_all(name)
if isinstance(sub, DataSub)]
def get_all_subs(self):
"""Gets all elements"""
return [sub for sub in self.data
if isinstance(sub, DataSub)]
def remove_macros(self, name):
for macro in self.get_macros(name):
self.remove(macro)
def get_binary_val(self, name, default = None):
"""For the lazy."""
binary = self.get_binary(name)
if binary: return binary.data
return default
def get_text_val(self, name, default = None):
"""For the lazy."""
text = self.get_text(name)
if text: return text.data
return default
def set_text_val(self, name, value, delete_if = None, translatable = False,
textdomain = ""):
"""For the lazy."""
text = self.get_text(name)
if text:
if value == delete_if:
self.remove(text)
else:
text.data = value
text.textdomain = textdomain
text.translatable = translatable
else:
if value != delete_if:
self.insert_text(name, value, translatable = translatable,
textdomain = textdomain)
def get_comment(self, start):
for item in self.get_all("comment"):
if isinstance(item, DataComment):
if item.data.startswith(start): return item
return None
def set_comment_first(self, comment):
"""For the lazy."""
for item in self.get_all("comment"):
if isinstance(item, DataComment):
if item.data == comment: return
self.insert_first(DataComment("comment", comment))
def get_quantity(self, tag, difficulty, default = None):
"""For the even lazier, looks for a value inside a difficulty ifdef.
"""
v = self.get_text_val(tag)
if v != None: return v
for ifdef in self.get_ifdefs(["EASY", "NORMAL", "HARD"][difficulty]):
v = ifdef.get_text_val(tag)
if v != None: return v
return default
def set_quantity(self, name, difficulty, value):
"""Sets one of 3 values of a quantity. If it doesn't exist yet, also the
other difficulties get the same value.
"""
value = str(value)
# read existing values
q = []
for d in xrange(3):
q += [self.get_quantity(name, d, value)]
q[difficulty] = value
# remove current tags
self.remove_text(name)
for ifdef in self.get_ifdefs("EASY") + self.get_ifdefs("NORMAL") + self.get_ifdefs("HARD"):
ifdef.remove_text(name)
# insert updated item
if q[0] == q[1] == q[2]:
self.set_text_val(name, value)
else:
for d in xrange(3):
ifdef = self.get_or_create_ifdef(["EASY", "NORMAL", "HARD"][d])
ifdef.set_text_val(name, q[d])
def debug(self, show_contents = False, use_color = False, indent=0, write=True):
if use_color:
red = "\x1b[31;1m"
off = "\x1b[0m"
else:
red = off = ""
pos = indent * " "
result = pos + "\ " + red + self.name + off + " (" + self.__class__.__name__ + ")\n"
if write:
sys.stdout.write( result )
indent += 1
for child in self.data:
cresult = child.debug(show_contents, use_color, indent, write=write)
if not write:
result += "\n" + cresult
indent -= 1
if not write:
return result
class DataIfDef(DataSub):
"""
An #ifdef section in WML.
"""
def __init__(self, name, sub, type):
DataSub.__init__(self, name, sub)
self.type = type
def copy(self):
copy = DataSub.copy(self)
copy.type = self.type
return copy
def read_file(filename, root_name = "WML"):
"""
Read in a file from disk and return a WML data object, with the WML in the
file placed under an entry with the name root_name.
"""
parser = wmlparser.Parser(None)
parser.parse_file(filename)
data = DataSub(root_name)
parser.parse_top(data)
return data