Some optimizations to glifLib

This commit is contained in:
Adrien Tétar 2017-11-04 19:37:01 +01:00
parent 3d891631d9
commit f0d67574ab

View File

@ -128,17 +128,17 @@ class GlyphSet(object):
Rebuild the contents dict by loading contents.plist. Rebuild the contents dict by loading contents.plist.
""" """
contentsPath = os.path.join(self.dirName, "contents.plist") contentsPath = os.path.join(self.dirName, "contents.plist")
if not os.path.exists(contentsPath): try:
contents = self._readPlist(contentsPath)
except KeyError:
# missing, consider the glyphset empty. # missing, consider the glyphset empty.
contents = {} contents = {}
else:
contents = self._readPlist(contentsPath)
# validate the contents # validate the contents
invalidFormat = False invalidFormat = False
if not isinstance(contents, dict): if not isinstance(contents, dict):
invalidFormat = True invalidFormat = True
else: else:
for name, fileName in list(contents.items()): for name, fileName in contents.items():
if not isinstance(name, basestring): if not isinstance(name, basestring):
invalidFormat = True invalidFormat = True
if not isinstance(fileName, basestring): if not isinstance(fileName, basestring):
@ -179,14 +179,16 @@ class GlyphSet(object):
def readLayerInfo(self, info): def readLayerInfo(self, info):
path = os.path.join(self.dirName, LAYERINFO_FILENAME) path = os.path.join(self.dirName, LAYERINFO_FILENAME)
if not os.path.exists(path): try:
infoDict = self._readPlist(path)
except KeyError:
# no info file, abort
return return
infoDict = self._readPlist(path)
if not isinstance(infoDict, dict): if not isinstance(infoDict, dict):
raise GlifLibError("layerinfo.plist is not properly formatted.") raise GlifLibError("layerinfo.plist is not properly formatted.")
infoDict = validateLayerInfoVersion3Data(infoDict) infoDict = validateLayerInfoVersion3Data(infoDict)
# populate the object # populate the object
for attr, value in list(infoDict.items()): for attr, value in infoDict.items():
try: try:
setattr(info, attr, value) setattr(info, attr, value)
except AttributeError: except AttributeError:
@ -197,7 +199,7 @@ class GlyphSet(object):
raise GlifLibError("layerinfo.plist is not allowed in UFO %d." % self.ufoFormatVersion) raise GlifLibError("layerinfo.plist is not allowed in UFO %d." % self.ufoFormatVersion)
# gather data # gather data
infoData = {} infoData = {}
for attr in list(layerInfoVersion3ValueData.keys()): for attr in layerInfoVersion3ValueData.keys():
if hasattr(info, attr): if hasattr(info, attr):
try: try:
value = getattr(info, attr) value = getattr(info, attr)
@ -242,10 +244,14 @@ class GlyphSet(object):
needRead = True needRead = True
if needRead: if needRead:
fileName = self.contents[glyphName] fileName = self.contents[glyphName]
if not os.path.exists(path): try:
raise KeyError(glyphName) with open(path, "rb") as f:
with open(path, "rb") as f: text = f.read()
text = f.read() except IOError as e:
# FileNotFoundError
if e.errno == 2:
raise KeyError(glyphName)
raise
self._glifCache[glyphName] = (text, os.path.getmtime(path)) self._glifCache[glyphName] = (text, os.path.getmtime(path))
return self._glifCache[glyphName][0] return self._glifCache[glyphName][0]
@ -413,7 +419,7 @@ class GlyphSet(object):
""" """
components = {} components = {}
if glyphNames is None: if glyphNames is None:
glyphNames = list(self.contents.keys()) glyphNames = self.contents.keys()
for glyphName in glyphNames: for glyphName in glyphNames:
text = self.getGLIF(glyphName) text = self.getGLIF(glyphName)
components[glyphName] = _fetchComponentBases(text) components[glyphName] = _fetchComponentBases(text)
@ -428,7 +434,7 @@ class GlyphSet(object):
""" """
images = {} images = {}
if glyphNames is None: if glyphNames is None:
glyphNames = list(self.contents.keys()) glyphNames = self.contents.keys()
for glyphName in glyphNames: for glyphName in glyphNames:
text = self.getGLIF(glyphName) text = self.getGLIF(glyphName)
images[glyphName] = _fetchImageFileName(text) images[glyphName] = _fetchImageFileName(text)
@ -441,7 +447,10 @@ class GlyphSet(object):
with open(path, "rb") as f: with open(path, "rb") as f:
data = readPlist(f) data = readPlist(f)
return data return data
except: except Exception as e:
# FileNotFoundError
if isinstance(e, IOError) and e.errno == 2:
raise KeyError()
raise GlifLibError("The file %s could not be read." % path) raise GlifLibError("The file %s could not be read." % path)
@ -454,9 +463,9 @@ def glyphNameToFileName(glyphName, glyphSet):
Wrapper around the userNameToFileName function in filenames.py Wrapper around the userNameToFileName function in filenames.py
""" """
if glyphSet: if glyphSet:
existing = [name.lower() for name in list(glyphSet.contents.values())] existing = frozenset(name.lower() for name in glyphSet.contents.values())
else: else:
existing = [] existing = frozenset()
if not isinstance(glyphName, unicode): if not isinstance(glyphName, unicode):
try: try:
new = unicode(glyphName) new = unicode(glyphName)
@ -595,13 +604,13 @@ def _writeAdvance(glyphObject, writer):
if not isinstance(width, (int, float)): if not isinstance(width, (int, float)):
raise GlifLibError("width attribute must be int or float") raise GlifLibError("width attribute must be int or float")
if width == 0: if width == 0:
width = None width = None
height = getattr(glyphObject, "height", None) height = getattr(glyphObject, "height", None)
if height is not None: if height is not None:
if not isinstance(height, (int, float)): if not isinstance(height, (int, float)):
raise GlifLibError("height attribute must be int or float") raise GlifLibError("height attribute must be int or float")
if height == 0: if height == 0:
height = None height = None
if width is not None and height is not None: if width is not None and height is not None:
writer.simpletag("advance", width=repr(width), height=repr(height)) writer.simpletag("advance", width=repr(width), height=repr(height))
writer.newline() writer.newline()
@ -789,16 +798,13 @@ def validateLayerInfoVersion3Data(infoData):
a set range of possible values for an attribute, that the a set range of possible values for an attribute, that the
value is in the accepted range. value is in the accepted range.
""" """
validInfoData = {} for attr, value in infoData.items():
for attr, value in list(infoData.items()):
if attr not in layerInfoVersion3ValueData: if attr not in layerInfoVersion3ValueData:
raise GlifLibError("Unknown attribute %s." % attr) raise GlifLibError("Unknown attribute %s." % attr)
isValidValue = validateLayerInfoVersion3ValueForAttribute(attr, value) isValidValue = validateLayerInfoVersion3ValueForAttribute(attr, value)
if not isValidValue: if not isValidValue:
raise GlifLibError("Invalid value for attribute %s (%s)." % (attr, repr(value))) raise GlifLibError("Invalid value for attribute %s (%s)." % (attr, repr(value)))
else: return infoData
validInfoData[attr] = value
return validInfoData
# ----------------- # -----------------
# GLIF Tree Support # GLIF Tree Support
@ -1067,7 +1073,7 @@ def _buildOutlineContourFormat1(pen, contour):
pen.endPath() pen.endPath()
def _buildOutlinePointsFormat1(pen, contour): def _buildOutlinePointsFormat1(pen, contour):
for index, element in enumerate(contour): for element in contour:
x = element.attrib["x"] x = element.attrib["x"]
y = element.attrib["y"] y = element.attrib["y"]
segmentType = element.attrib["segmentType"] segmentType = element.attrib["segmentType"]
@ -1078,8 +1084,9 @@ def _buildOutlinePointsFormat1(pen, contour):
def _buildOutlineComponentFormat1(pen, component): def _buildOutlineComponentFormat1(pen, component):
if len(component): if len(component):
raise GlifLibError("Unknown child elements of component element.") raise GlifLibError("Unknown child elements of component element.")
if set(component.attrib.keys()) - componentAttributesFormat1: for attr in component.attrib.keys():
raise GlifLibError("Unknown attributes in component element.") if attr not in componentAttributesFormat1:
raise GlifLibError("Unknown attributes in component element.")
baseGlyphName = component.get("base") baseGlyphName = component.get("base")
if baseGlyphName is None: if baseGlyphName is None:
raise GlifLibError("The base attribute is not defined in the component.") raise GlifLibError("The base attribute is not defined in the component.")
@ -1125,7 +1132,7 @@ def _buildOutlineContourFormat2(pen, contour, identifiers):
pen.endPath() pen.endPath()
def _buildOutlinePointsFormat2(pen, contour, identifiers): def _buildOutlinePointsFormat2(pen, contour, identifiers):
for index, element in enumerate(contour): for element in contour:
x = element.attrib["x"] x = element.attrib["x"]
y = element.attrib["y"] y = element.attrib["y"]
segmentType = element.attrib["segmentType"] segmentType = element.attrib["segmentType"]
@ -1147,8 +1154,9 @@ def _buildOutlinePointsFormat2(pen, contour, identifiers):
def _buildOutlineComponentFormat2(pen, component, identifiers): def _buildOutlineComponentFormat2(pen, component, identifiers):
if len(component): if len(component):
raise GlifLibError("Unknown child elements of component element.") raise GlifLibError("Unknown child elements of component element.")
if set(component.attrib.keys()) - componentAttributesFormat2: for attr in component.attrib.keys():
raise GlifLibError("Unknown attributes in component element.") if attr not in componentAttributesFormat2:
raise GlifLibError("Unknown attributes in component element.")
baseGlyphName = component.get("base") baseGlyphName = component.get("base")
if baseGlyphName is None: if baseGlyphName is None:
raise GlifLibError("The base attribute is not defined in the component.") raise GlifLibError("The base attribute is not defined in the component.")
@ -1187,21 +1195,25 @@ def _validateAndMassagePointStructures(contour, pointAttributes, openContourOffC
if element.tag != "point": if element.tag != "point":
raise GlifLibError("Unknown child element (%s) of contour element." % element.tag) raise GlifLibError("Unknown child element (%s) of contour element." % element.tag)
# unknown attributes # unknown attributes
unknownAttributes = [attr for attr in list(element.attrib.keys()) if attr not in pointAttributes] for attr in element.attrib.keys():
if unknownAttributes: if attr not in pointAttributes:
raise GlifLibError("Unknown attributes in point element.") raise GlifLibError("Unknown attribute in point element: %s" % attr)
# search for unknown children # search for unknown children
if len(element): if len(element):
raise GlifLibError("Unknown child elements in point element.") raise GlifLibError("Unknown child elements in point element.")
# x and y are required # x and y are required
x = element.get("x") for attr in ("x", "y"):
y = element.get("y") value = element.get(attr)
if x is None: if value is None:
raise GlifLibError("Required x attribute is missing in point element.") raise GlifLibError("Required %s attribute is missing in point element." % attr)
if y is None: try:
raise GlifLibError("Required y attribute is missing in point element.") value = int(value)
element.attrib["x"] = _number(x) except ValueError:
element.attrib["y"] = _number(y) try:
value = float(value)
except ValueError:
raise GlifLibError("Invalid %s value in point element: %s" % (attr, value))
element.attrib[attr] = value
# segment type # segment type
pointType = element.attrib.pop("type", "offcurve") pointType = element.attrib.pop("type", "offcurve")
if pointType not in pointTypeOptions: if pointType not in pointTypeOptions:
@ -1243,8 +1255,7 @@ def _validateAndMassagePointStructures(contour, pointAttributes, openContourOffC
# we only care about how many offCurves there are before an onCurve # we only care about how many offCurves there are before an onCurve
# filter out the trailing offCurves # filter out the trailing offCurves
offCurvesCount = len(contour) - 1 - lastOnCurvePoint offCurvesCount = len(contour) - 1 - lastOnCurvePoint
stripedContour = contour[:-offCurvesCount] if offCurvesCount else contour for element in contour:
for element in stripedContour:
segmentType = element.attrib["segmentType"] segmentType = element.attrib["segmentType"]
if segmentType is None: if segmentType is None:
offCurvesCount += 1 offCurvesCount += 1