Refactor multibyte text code to use a TextMapper

This commit is contained in:
Kevin Cathcart 2018-03-10 11:57:04 -05:00
parent ed6d66acd9
commit 93f77ddde3
1 changed files with 205 additions and 210 deletions

61
Text.py
View File

@ -504,14 +504,14 @@ def string_to_alttp_core(s, pause=True, wrap=14):
words.insert(0, word_rest)
lines.insert(0, ' '.join(words))
write_word(outbuf, word_first)
outbuf.extend(RawMBTextMapper.convert(word_first))
break
if wordlen(word) <= (linespace if linespace == wrap else linespace - 1):
if linespace < wrap:
word = ' ' + word
linespace -= wordlen(word)
write_word(outbuf, word)
outbuf.extend(RawMBTextMapper.convert(word))
else:
# ran out of space, push word and lines back and continue with next line
words.insert(0, word)
@ -607,15 +607,27 @@ def charlen(word, offset):
return (2, offset+1)
return (1, offset+1)
def write_word(buf, word):
for char in word:
res = char_to_alttp_char(char)
if isinstance(res, int):
buf.extend([0x00, res])
else:
buf.extend(res)
class TextMapper(object):
number_offset = None
alpha_offset = 0
char_map = {}
@classmethod
def map_char(cls, char):
if cls.number_offset is not None:
if 0x30 <= ord(char) <= 0x39:
return ord(char) + cls.number_offset
if 0x61 <= ord(char) <= 0x7A:
return ord(char) + cls.alpha_offset
return cls.char_map.get(char, cls.char_map[' '])
@classmethod
def convert(cls, text):
buf = bytearray()
for char in text.lower():
buf.append(cls.map_char(char))
return buf
class RawMBTextMapper(TextMapper):
char_map = {' ': 0xFF,
'?': 0xC6,
'!': 0xC7,
@ -804,35 +816,18 @@ char_map = {' ': 0xFF,
'': 0x9D,
'': 0x9E,
'': 0x9F}
def char_to_alttp_char(char):
if 0x30 <= ord(char) <= 0x39:
return ord(char) + 0x70
if 0x41 <= ord(char) <= 0x5A:
return ord(char) + 0x69
return char_map.get(char, 0xFF)
class TextMapper(object):
number_offset = None
alpha_offset = 0
char_map = {}
@classmethod
def map_char(cls, char):
if cls.number_offset is not None:
if 0x30 <= ord(char) <= 0x39:
return ord(char) + cls.number_offset
if 0x61 <= ord(char) <= 0x7A:
return ord(char) + cls.alpha_offset
return cls.char_map.get(char, cls.char_map[' '])
alpha_offset = 0x69
number_offset = 0x70
@classmethod
def convert(cls, text):
buf = bytearray()
for char in text.lower():
buf.append(cls.map_char(char))
res = cls.map_char(char)
if isinstance(res, int):
buf.extend([0x00, res])
else:
buf.extend(res)
return buf