aboutsummaryrefslogtreecommitdiff
path: root/tools/themeparser.py
blob: 98fefcb3141d0d784a3f9cd776d3929281be6cac (plain)
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
#!/usr/bin/env python
# encoding: utf-8

"""
 " ScummVM - Graphic Adventure Engine
 "
 " ScummVM is the legal property of its developers, whose names
 " are too numerous to list here. Please refer to the COPYRIGHT
 " file distributed with this source distribution.
 "
 " This program 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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
 "
 " $URL$
 " $Id$
"""

from __future__ import with_statement
import os
import xml.dom.minidom as DOM
import struct
from UserDict import UserDict

def printBinaryDump(buf):
	LINE_WIDTH = 16
	
	def buildRepr(line):
		out = ""
		for c in line:
			out += '.' if ord(c) < 0x20 or ord(c) > 0x7E else c
		return out
	
	print "Binary dump of %d BYTES:\n" % len(buf)
	for i in xrange(len(buf) // LINE_WIDTH):
		bufLine = buf[LINE_WIDTH * i : LINE_WIDTH * (i + 1)]
		
		print "| %s | %s |" % (" ".join(["%0.2X" % ord(c) for c in bufLine]), buildRepr(bufLine))
		
	bufLine = buf[-(len(buf) % LINE_WIDTH):]
	print "| %s%s | %s%s |" % (
		" ".join(["%0.2X" % ord(c) for c in bufLine]), 
		'   ' * (LINE_WIDTH - len(bufLine)), 
		buildRepr(bufLine),
		' ' * (LINE_WIDTH - len(bufLine))
	)
	
	print ""

def pbin(data):
	return str(map(lambda c: hex(ord(c)), data))
#	return " ".join(["%0.2X" % ord(c) for c in data])

class STXBinaryFile:
	class InvalidRGBColor(Exception):
		pass
		
	class InvalidResolution(Exception):
		pass
		
	class InvalidFontIdentifier(Exception):
		pass
		
	class InvalidBitmapName(Exception):
		pass
		
	class DrawStepData:
		def __init__(self, isDefault, packFormat, function):
			self.isDefault = isDefault
			self.packFormat = packFormat
			self.parse = function
		
	BYTEORDER = '>' # big-endian format by default, platform independent
		
	TRUTH_VALUES = {"" : 0, "true" : 1, "false" : 0, "True" : 1, "False" : 0}
		
	BLOCK_HEADERS = {
		"bitmaps" 	: 0x0100000A,
		"fonts"		: 0x0100000B,
		"cursor"	: 0x0100000C,
		"drawdata"	: 0x0100000D
	}
	
	DS_triangleOrientations = {"top" : 0x1, "bottom" : 0x2, "left" : 0x3, "right" : 0x4}
	DS_fillModes = {"none" : 0x0, "foreground" : 0x1, "background" : 0x2, "gradient" : 0x3}
	DS_vectorAlign = {"left" : 0x1, "right" : 0x2, "bottom" : 0x3, "top" : 0x4, "center" : 0x5}
   
	DS_functions = {
		"void" : 0x0, "circle" : 0x1, "square" : 0x2, "roundedsq" : 0x3, "bevelsq" : 0x4, 
   		"line" : 0x5, "triangle" : 0x6, "fill" : 0x7, "tab" : 0x8, "bitmap" : 0x9, "cross" : 0xA
	}
	
	DS_fonts = {
		"text_default" : 0x0, "text_hover" : 0x1, "text_disabled" : 0x2, 
		"text_inverted" : 0x3, "text_button" : 0x4, "text_button_hover" : 0x5, "text_normal" : 0x6
	}
	
	DS_text_alignV = {"bottom" : 0x0, "center" : 0x1, "top" : 0x2}
	DS_text_alignH = {"left" : 0x0, "center" : 0x1, "right" : 0x2}
	
	DS_list = [
		"func", "fill", "stroke", "gradient_factor",
		"width", "height", "xpos", "ypos",
		"radius", "bevel", "shadow", "orientation", "file",
		"fg_color", "bg_color", "gradient_start", "gradient_end", "bevel_color"
	]
	
	def __init__(self, themeName, autoLoad = True, verbose = False):
		self._themeName = themeName
		self._stxFiles = []
		self._verbose = verbose
		
		self.DS_data = {
		#	attribute name						isDefault	pack	parse function
			"func"				: self.DrawStepData(False,	"B",	lambda f: self.DS_functions[f]),
			"fill"				: self.DrawStepData(True, 	"B",	lambda f: self.DS_fillModes[f]),
			"stroke" 			: self.DrawStepData(True,	"B",	int),
			"gradient_factor" 	: self.DrawStepData(True, 	"B",	int),
			"width"				: self.DrawStepData(False, 	"i", 	lambda w: -1 if w == 'height' else 0 if w == 'auto' else int(w)),
			"height"			: self.DrawStepData(False, 	"i",	lambda h: -1 if h == 'width' else 0 if h == 'auto' else int(h)),
			"xpos"				: self.DrawStepData(False,	"i",	lambda pos: self.DS_vectorAlign[pos] if pos in self.DS_vectorAlign else int(pos)),
			"ypos"				: self.DrawStepData(False,	"i", 	lambda pos: self.DS_vectorAlign[pos] if pos in self.DS_vectorAlign else int(pos)),
			"radius"			: self.DrawStepData(False,	"i",	lambda r: 0xFF if r == 'auto' else int(r)),
			"bevel" 			: self.DrawStepData(True, 	"B", 	int),
			"shadow" 			: self.DrawStepData(True, 	"B", 	int),
			"orientation"		: self.DrawStepData(False,	"B", 	lambda o: self.DS_triangleOrientations[o]),
			"file"				: self.DrawStepData(False,	"B",	self.__getBitmap),
			"fg_color"			: self.DrawStepData(True, 	"4s",	self.__parseColor),
			"bg_color"			: self.DrawStepData(True, 	"4s",	self.__parseColor),
			"gradient_start"	: self.DrawStepData(True, 	"4s",	self.__parseColor),
			"gradient_end"		: self.DrawStepData(True, 	"4s",	self.__parseColor),
			"bevel_color"		: self.DrawStepData(True, 	"4s",	self.__parseColor)
		}
		
		if autoLoad:
			if not os.path.isdir(themeName) or not os.path.isfile(os.path.join(themeName, "THEMERC")):
				raise IOError
				
			for filename in os.listdir(themeName):
				filename = os.path.join(themeName, filename)
				if os.path.isfile(filename) and filename.endswith('.stx'):
					self._stxFiles.append(filename)
					
	def debug(self, text):
		if self._verbose: print text
		
	def debugBinary(self, data):
		if self._verbose:
			print "BINARY OUTPUT (%d bytes):" % len(data), " ".join(["%0.2X" % ord(c) for c in data])
			
	def addSTXFile(self, filename):
		if not os.path.isfile(filename):
			raise IOError
		else:
			self._stxFiles.append(filename) 
		
	def parse(self):
		if not self._stxFiles:
			self.debug("No files have been loaded for parsing on the theme.")
			raise IOError
		
		for f in self._stxFiles:
			self.debug("Parsing %s." % f)
			with open(f) as stxFile:
				self.__parseFile(stxFile)
	
	def __parseFile(self, xmlFile):
		stxDom = DOM.parse(xmlFile)
		
		for layout in stxDom.getElementsByTagName("layout_info"):
			self.__parseLayout(layout)

		for render in stxDom.getElementsByTagName("render_info"):
			self.__parseRender(render)
		
		stxDom.unlink()
		
	def __getBitmap(self, bmp):
		bmp = str(bmp)
		
		if bmp == "":
			return 0x0
		
		if bmp not in self._bitmaps:
			raise self.InvalidBitmapName
		
		return self._bitmaps[bmp]
		
	def __parseDrawStep(self, drawstepDom, localDefaults = {}):
		
		dstable = {}
		
		if drawstepDom.tagName == "defaults":
			isGlobal = drawstepDom.parentNode.tagName == "render_info"
			
			for ds in self.DS_list:
				if self.DS_data[ds].isDefault and drawstepDom.hasAttribute(ds):
					dstable[ds] = self.DS_data[ds].parse(drawstepDom.getAttribute(ds))
					
				elif isGlobal:
					dstable[ds] = None
		
		else:
			for ds in self.DS_data:
				if drawstepDom.hasAttribute(ds):
					dstable[ds] = self.DS_data[ds].parse(drawstepDom.getAttribute(ds))
				elif self.DS_data[ds].isDefault:
					dstable[ds] = localDefaults[ds] if ds in localDefaults else self._globalDefaults[ds]
				else:
					dstable[ds] = None
		
		return dstable
		
		
	def __parseDrawStepToBin(self, stepDict):
		"""
			/BBBBiiiiiBBB4s4s4s4s4sB/ == 
			function 		(byte)
			fill 			(byte)
			stroke			(byte)
			gradient_factor	(byte)
			width			(int32)
			height			(int32)
			xpos			(int32)
			ypos			(int32)
			radius			(int32)
			bevel			(byte)
			shadow			(byte)
			orientation 	(byte)
			file			(byte)
			fg_color		(4 byte)
			bg_color		(4 byte)
			gradient_start 	(4 byte)
			gradient_end	(4 byte)
			bevel_color		(4 byte)
		"""
		
		packLayout = ""
		packData = []
		
		for ds in self.DS_list:
			layout = self.DS_data[ds].packFormat
			data = stepDict[ds]

			if not data:
				size = struct.calcsize(layout)
				packLayout += "B" * size
				
				for d in xrange(size):
					packData.append(0)
			else:
				packLayout += layout
				packData.append(data)
			
					
		stepBin = struct.pack(self.BYTEORDER + packLayout, *tuple(packData))
		return stepBin
			
		
	def __parseResolutionToBin(self, resString):
		"""
			/B bHH bHH bHH/ == 1 byte + x * 9 bytes
			number of resolution sections (byte)
			exclude resolution (byte)
			resolution X (half)
			resolution Y (half)
		"""
		
		if resString == "":
			return struct.pack(self.BYTEORDER + "BbHH", 1, 0, 0, 0)
			
		resolutions = resString.split(", ")
		packFormat = "B" + "bHH" * len(resolutions)
		packData = [len(resolutions)]
			
		for res in resolutions:
			exclude = 0
			if res[0] == '-':
				exclude = 1
				res = res[1:]
			
			try:
				x, y = res.split('x')
				x = 0 if x == 'X' else int(x)
				y = 0 if y == 'Y' else int(y)
			except ValueError:
				raise InvalidResolution
			
			packData.append(exclude)
			packData.append(x)
			packData.append(y)
		
		buff = struct.pack(self.BYTEORDER + packFormat, *tuple(packData))
		return buff
		
	def __parseRGBToBin(self, color):
		"""
			/xBBB/ == 32 bits
			padding (byte)
			red color (byte)
			green color (byte)
			blue color (byte)
		"""
		
		try:
			rgb = tuple(map(int, color.split(", ")))
		except ValueError:
			raise self.InvalidRGBColor
		
		if len(rgb) != 3:
			raise self.InvalidRGBColor
			
		for c in rgb:
			if c < 0 or c > 255:
				raise self.InvalidRGBColor
				
		rgb = struct.pack(self.BYTEORDER + "xBBB", *tuple(rgb))
		
#		self.debugBinary(rgb)
		return rgb
		
	def __parseColor(self, color):
		try:
			color = self.__parseRGBToBin(color)
		except self.InvalidRGBColor:
			if color not in self._colors:
				raise self.InvalidRGBColor
			color = self._colors[color]
			
		return color
		
		
	def __parsePalette(self, paletteDom):
		self._colors = {}		
		
		for color in paletteDom.getElementsByTagName("color"):
			color_name = color.getAttribute('name')
			color_rgb = self.__parseRGBToBin(color.getAttribute('rgb'))
			
			self._colors[color_name] = color_rgb
			self.debug("COLOR: %s" % (color_name))
			
	
	def __parseBitmaps(self, bitmapsDom):
		self._bitmaps = {}
		idCount = 0xA0
		packLayout = ""
		packData = []
		
		for bitmap in bitmapsDom.getElementsByTagName("bitmap"):
			bmpName = str(bitmap.getAttribute("filename"))
			self._bitmaps[bmpName] = idCount
			
			packLayout += "B%ds" % (len(bmpName) + 1)
			packData.append(idCount)
			packData.append(bmpName)
			idCount += 1
			
			
		bitmapBinary = struct.pack(
			self.BYTEORDER + "IB" + packLayout,
			self.BLOCK_HEADERS['bitmaps'],
			len(bitmapsDom.getElementsByTagName("bitmap")),
			*tuple(packData)
		)
		
		self.debug("BITMAPS:\n%s\n\n" % pbin(bitmapBinary))
		return bitmapBinary
			
	def __parseFonts(self, fontsDom):
		"""
			/IB Bs4ss .../
			section header (uint32)
			number of font definitions (byte)
			
			id for font definition (byte)
			resolution for font (byte array)
			color for font (4 bytes)
			font filename (byte array, null terminated)
		"""
		
		packLayout = ""
		packData = []

		for font in fontsDom.getElementsByTagName("font"):
			ident = font.getAttribute("id")
			
			if ident not in self.DS_fonts:
				raise self.InvalidFontIdentifier
			
			color = self.__parseColor(font.getAttribute("color"))
			filename = str(font.getAttribute("file"))
			
			if filename == 'default':
				filename = ''
			
			resolution = self.__parseResolutionToBin(font.getAttribute("resolution"))
			
			packLayout += "B%ds4s%ds" % (len(resolution), len(filename) + 1)
			packData.append(self.DS_fonts[ident])
			packData.append(resolution)
			packData.append(color)
			packData.append(filename)			
		
		fontsBinary = struct.pack(self.BYTEORDER + \
			"IB" + packLayout, 
			self.BLOCK_HEADERS['fonts'], 
			len(fontsDom.getElementsByTagName("font")),
			*tuple(packData)
		)
			
		
		self.debug("FONTS DATA:\n%s\n\n" % pbin(fontsBinary))
		return fontsBinary
			
	def __parseTextToBin(self, textDom):
		"""
			/BBBx/
			font identifier (byte)
			vertical alignment (byte)
			horizontal alignment (byte)
			padding until word (byte)
		"""
		
		font = textDom.getAttribute("font")
		if font not in self.DS_fonts:
			raise self.InvalidFontIdentifier
		
		textBin = struct.pack(self.BYTEORDER + "BBBx",
			self.DS_fonts[font],
			self.DS_text_alignV[textDom.getAttribute("vertical_align")],
			self.DS_text_alignH[textDom.getAttribute("horizontal_align")]
		)
		
		return textBin
			
	def __parseDrawData(self, ddDom):
		"""
			/IsIBBHss/
				Section Header (uint32)
				Resolution (byte array, word-aligned)
				DrawData id hash (uint32)
				Cached (byte)
				has text section? (byte)
				number of DD sections (uint16)
				** text segment (4 bytes)
				drawstep segments (byte array)
		"""
				
		
		localDefaults = ddDom.getElementsByTagName("defaults")
		localDefaults = localDefaults[0] if localDefaults else {}
		
		stepList = []
		
		for ds in ddDom.getElementsByTagName("drawstep"):
			dstable = self.__parseDrawStep(ds, localDefaults)
			dsbinary = self.__parseDrawStepToBin(dstable)
			
			stepList.append(dsbinary)

		stepByteArray = "".join(stepList)
		
		resolution = self.__parseResolutionToBin(ddDom.getAttribute("resolution"))
		
		text = ddDom.getElementsByTagName("text")
		text = self.__parseTextToBin(text[0]) if text else ""
		
		id_hash = str.__hash__(str(ddDom.getAttribute("id"))) & 0xFFFFFFFF
		cached = self.TRUTH_VALUES[ddDom.getAttribute("cached")]
			
		ddBinary = struct.pack(self.BYTEORDER + \
			"I%dsIBBH4s%ds" % (len(resolution), len(stepByteArray)),
			
			self.BLOCK_HEADERS['drawdata'], # Section Header (uint32)
			resolution,						# Resolution (byte array, word-aligned)
			id_hash,						# DrawData id hash (uint32)
			cached,							# Cached (byte)
			0x1 if text else 0x0,			# has text section? (byte)
			len(stepList),					# number of DD sections (uint16)
			text,							# ** text segment (byte array)
			stepByteArray					# drawstep segments (byte array)
		)
		
		self.debug("DRAW DATA %s (%X): \n" % (ddDom.getAttribute("id"), id_hash) + pbin(ddBinary) + "\n\n")
		return ddBinary
		
	def __parseCursor(self, cursorDom):
		"""
			/IsBBhh/
			section header (uint32)
			resolution string (byte array)
			bitmap id (byte)
			scale (byte)
			hotspot X (half)
			hotspot Y (half)
		"""
	
		resolution = self.__parseResolutionToBin(cursorDom.getAttribute("resolution"))
		scale = int(cursorDom.getAttribute("scale"))
		hsX, hsY = cursorDom.getAttribute("hotspot").split(", ")
	
		cursorBin = struct.pack(self.BYTEORDER + "I%dsBBhh" % len(resolution),
			self.BLOCK_HEADERS['cursor'],
			resolution,
			self.__getBitmap(cursorDom.getAttribute("file")),
			scale,
			int(hsX),
			int(hsY)
		)
		
		self.debug("CURSOR:\n%s\n\n" % pbin(cursorBin))
		return cursorBin
		
		
	def __parseLayout(self, layoutDom):
		self.debug("GLOBAL SECTION: LAYOUT INFO.")
		
	def __parseRender(self, renderDom):
		self.debug("GLOBAL SECTION: RENDER INFO.")
		
		paletteDom = renderDom.getElementsByTagName("palette")[0]
		bitmapsDom = renderDom.getElementsByTagName("bitmaps")[0]
		fontsDom = renderDom.getElementsByTagName("fonts")[0]
		defaultsDom = renderDom.getElementsByTagName("defaults")[0]
		
		self.__parsePalette(paletteDom)
		
		bitmapBIN 	= self.__parseBitmaps(bitmapsDom)
		fontsBIN 	= self.__parseFonts(fontsDom)
		cursorBIN 	= ""
		drawdataBIN = ""
		
		for cur in renderDom.getElementsByTagName("cursor"):
			cursorBIN += self.__parseCursor(cur)
		
		self._globalDefaults = self.__parseDrawStep(defaultsDom)
		
		for dd in renderDom.getElementsByTagName("drawdata"):
			drawdataBIN += self.__parseDrawData(dd)


		renderInfoBIN = bitmapBIN + fontsBIN + cursorBIN + drawdataBIN
		printBinaryDump(renderInfoBIN)
		
		return renderInfoBIN

if __name__ == '__main__':
	bin = STXBinaryFile('../gui/themes/scummmodern', True, True)
	bin.parse()