Don't assume anything about the structure of GLIF that is not part of the spec.

git-svn-id: http://svn.robofab.com/trunk@234 b5fa9d6c-a76f-4ffd-b3cb-f825fc41095c
This commit is contained in:
Tal Leming 2011-04-28 00:29:06 +00:00
parent 9ae34cc649
commit 62d81b2b9e

View File

@ -536,28 +536,36 @@ def _fetchGlyphName(glyphPath):
def _fetchUnicodes(text): def _fetchUnicodes(text):
# Given GLIF text, get a list of all unicode values from the XML data. # Given GLIF text, get a list of all unicode values from the XML data.
# NOTE: this assumes .glif files written by glifLib, since parser = _FetchUnicodesParser(text)
# we simply stop parsing as soon as we see anything else than return parser.unicodes
# <glyph>, <advance> or <unicode>. glifLib always writes those
# elements in that order, before anything else.
from xml.parsers.expat import ParserCreate
unicodes = [] class _FetchUnicodesParser(object):
def _startElementHandler(tagName, attrs, _unicodes=unicodes):
if tagName == "unicode":
_unicodes.append(int(attrs["hex"], 16))
elif tagName not in ("glyph", "advance"):
raise _DoneParsing()
p = ParserCreate() def __init__(self, text):
p.StartElementHandler = _startElementHandler from xml.parsers.expat import ParserCreate
p.returns_unicode = True self.unicodes = []
f = StringIO(text) self._elementStack = []
try: parser = ParserCreate()
p.ParseFile(f) parser.returns_unicode = 0 # XXX, Don't remember why. It sucks, though.
except _DoneParsing: parser.StartElementHandler = self.startElementHandler
pass parser.EndElementHandler = self.endElementHandler
return unicodes parser.Parse(text)
def startElementHandler(self, name, attrs):
if name == "unicode" and len(self._elementStack) == 1 and self._elementStack[0] == "glyph":
value = attrs.get("hex")
if value is None:
raise GlifLibError("The required hex attribute not defined in a unicode element.")
try:
value = int(value, 16)
except ValueError:
raise GlifLibError("The value for the hex attribute defined in a unicode element is not a valid value.")
self.unicodes.append(value)
self._elementStack.append(name)
def endElementHandler(self, name):
other = self._elementStack.pop(-1)
assert other == name
def buildOutline_Format0(pen, xmlNodes): def buildOutline_Format0(pen, xmlNodes):