#!/usr/bin/python -u # -*- coding: utf-8 -*- from defs import CHUNK_TYPE class StringBlock(): def __init__(self, reader): magic = reader.readInt() if magic != CHUNK_TYPE: raise Exception("Bad Magic Number (0x%08lx)!" % magic) chunk_size = reader.readInt() str_count = reader.readInt() style_offset_count = reader.readInt() reader.readInt() # ??? str_offset = reader.readInt() styles_offset = reader.readInt() self._str_offsets = reader.readIntArray(str_count); self._style_offsets = reader.readIntArray(style_offset_count); if styles_offset == 0: size = chunk_size - str_offset else: size = styles_offset - str_offset if size % 4 != 0: raise Exception("String data size is not multiple of 4 (%d)!" % size) self._strings = reader.readIntArray(size / 4) if styles_offset > 0: size = chunk_size - styles_offset if size % 4 != 0: raise Exception("Style data size is not multiple of 4 (%d)!" % size) self._styles = reader.readIntArray(size / 4) self._str_data = [ self.getRaw(i) for i in range(self.count()) ] def count(self): """Count the number of strings in the current block.""" return len(self._str_offsets) def getRaw(self, index): """Provide a raw string (without any styling information) at specified index.""" if index < 0 or index >= len(self._str_offsets): raise Exception("Invalid Index (%d)!" % index) offset = self._str_offsets[index] length = self.getShort(self._strings, offset) data = '' for i in range(length): offset += 2 data += unichr(self.getShort(self._strings, offset)) return data def getShort(self, array, offset): value = array[offset / 4] if ((offset % 4) / 2) == 0: value &= 0xFFFF else: value >>= 16 return value