Beispiel #1
0
 def fromXML(self, name, attrs, content, ttFont):
     if not hasattr(self, "metrics"):
         self.metrics = {}
     if name == "mtx":
         self.metrics[attrs["name"]] = (safeEval(attrs[self.advanceName]),
                                        safeEval(
                                            attrs[self.sideBearingName]))
	def fromXML(self, name, attrs, content, ttFont):
		if name == "palette":
			self.paletteLabels.append(int(attrs.get("label", self.NO_NAME_ID)))
			self.paletteTypes.append(int(attrs.get("type", self.DEFAULT_PALETTE_TYPE)))
			palette = []
			for element in content:
				if isinstance(element, basestring):
					continue
				attrs = element[1]
				color = Color.fromHex(attrs["value"])
				palette.append(color)
			self.palettes.append(palette)
		elif name == "paletteEntryLabels":
			colorLabels = {}
			for element in content:
				if isinstance(element, basestring):
					continue
				elementName, elementAttr, _ = element
				if elementName == "label":
					labelIndex = safeEval(elementAttr["index"])
					nameID = safeEval(elementAttr["value"])
					colorLabels[labelIndex] = nameID
			self.paletteEntryLabels = [
				colorLabels.get(i, self.NO_NAME_ID)
				for i in range(self.numPaletteEntries)]
		elif "value" in attrs:
			value = safeEval(attrs["value"])
			setattr(self, name, value)
			if name == "numPaletteEntries":
				self.paletteEntryLabels = [self.NO_NAME_ID] * self.numPaletteEntries
Beispiel #3
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == 'version':
         self.version = float(safeEval(attrs['version']))
         self.scheme = int(safeEval(attrs['compressionScheme']))
     if name != 'glyph': return
     if not hasattr(self, 'attributes'):
         self.attributes = {}
     gname = attrs['name']
     attributes = _Dict()
     for element in content:
         if not isinstance(element, tuple): continue
         tag, attrs, subcontent = element
         if tag == 'attribute':
             k = int(safeEval(attrs['index']))
             v = int(safeEval(attrs['value']))
             attributes[k] = v
         elif tag == 'octaboxes':
             self.hasOctaboxes = True
             o = _Object()
             o.subboxBitmap = int(attrs['bitmap'], 16)
             o.subboxes = []
             del attrs['bitmap']
             for k, v in attrs.items():
                 setattr(o, k, int(float(v[:-1]) * 255. / 100. + 0.5))
             for element in subcontent:
                 if not isinstance(element, tuple): continue
                 (tag, attrs, subcontent) = element
                 so = _Object()
                 for k, v in attrs.items():
                     setattr(so, k, int(float(v[:-1]) * 255. / 100. + 0.5))
                 o.subboxes.append(so)
             attributes.octabox = o
     self.attributes[gname] = attributes
 def fromXML(self, name, attrs, content, ttFont):
     if name != "gaspRange":
         return
     if not hasattr(self, "gaspRange"):
         self.gaspRange = {}
     self.gaspRange[safeEval(attrs["rangeMaxPPEM"])] = safeEval(
         attrs["rangeGaspBehavior"])
    def fromXML(self, name, attrs, content, ttFont):
        if name == 'header':
            self.version = safeEval(attrs['version'])
        elif name == 'strikedata':
            if not hasattr(self, 'strikeData'):
                self.strikeData = []
            strikeIndex = safeEval(attrs['index'])

            bitmapGlyphDict = {}
            for element in content:
                if not isinstance(element, tuple):
                    continue
                name, attrs, content = element
                if name[4:].startswith(_bitmapGlyphSubclassPrefix[4:]):
                    imageFormat = safeEval(
                        name[len(_bitmapGlyphSubclassPrefix):])
                    glyphName = attrs['name']
                    imageFormatClass = self.getImageFormatClass(imageFormat)
                    curGlyph = imageFormatClass(None, None)
                    curGlyph.fromXML(name, attrs, content, ttFont)
                    assert glyphName not in bitmapGlyphDict, "Duplicate glyphs with the same name '%s' in the same strike." % glyphName
                    bitmapGlyphDict[glyphName] = curGlyph
                else:
                    log.warning("%s being ignored by %s", name,
                                self.__class__.__name__)

            # Grow the strike data array to the appropriate size. The XML
            # format allows the strike index value to be out of order.
            if strikeIndex >= len(self.strikeData):
                self.strikeData += [None] * (strikeIndex + 1 -
                                             len(self.strikeData))
            assert self.strikeData[
                strikeIndex] is None, "Duplicate strike EBDT indices."
            self.strikeData[strikeIndex] = bitmapGlyphDict
Beispiel #6
0
	def fromXML(self, name, attrs, content, ttFont):
		self.language = 0xFF # provide a value so that CmapSubtable.__lt__() won't fail
		if not hasattr(self, "cmap"):
			self.cmap = {} # so that clients that expect this to exist in a cmap table won't fail.
		if not hasattr(self, "uvsDict"):
			self.uvsDict = {}
			uvsDict = self.uvsDict

		# For backwards compatibility reasons we accept "None" as an indicator
		# for "default mapping", unless the font actually has a glyph named
		# "None".
		_hasGlyphNamedNone = None

		for element in content:
			if not isinstance(element, tuple):
				continue
			name, attrs, content = element
			if name != "map":
				continue
			uvs = safeEval(attrs["uvs"])
			uv = safeEval(attrs["uv"])
			gname = attrs.get("name")
			if gname == "None":
				if _hasGlyphNamedNone is None:
					_hasGlyphNamedNone = "None" in ttFont.getGlyphOrder()
				if not _hasGlyphNamedNone:
					gname = None
			try:
				uvsDict[uvs].append((uv, gname))
			except KeyError:
				uvsDict[uvs] = [(uv, gname)]
Beispiel #7
0
	def fromXML(self, name, attrs, content, ttFont):
		if not hasattr(self, "values"):
			self.values = array.array("h")
		if name == "cv":
			index = safeEval(attrs["index"])
			value = safeEval(attrs["value"])
			for i in range(1 + index - len(self.values)):
				self.values.append(0)
			self.values[index] = value
 def fromXML(self, name, attrs, content, ttFont):
     if name == "tableHeader":
         self.signatureRecords = []
         self.ulVersion = safeEval(attrs["version"])
         self.usNumSigs = safeEval(attrs["numSigs"])
         self.usFlag = safeEval(attrs["flag"])
         return
     if name == "SignatureRecord":
         sigrec = SignatureRecord()
         sigrec.fromXML(name, attrs, content, ttFont)
         self.signatureRecords.append(sigrec)
Beispiel #9
0
 def fromXML(self, name, attrs, content, ttFont):
     self.track = str2fl(attrs['value'], 16)
     self.nameIndex = safeEval(attrs['nameIndex'])
     for element in content:
         if not isinstance(element, tuple):
             continue
         name, attrs, _ = element
         if name != 'track':
             continue
         size = str2fl(attrs['size'], 16)
         self[size] = safeEval(attrs['value'])
Beispiel #10
0
	def fromXML(self, name, attrs, content, ttFont):
		self.language = safeEval(attrs["language"])
		if not hasattr(self, "cmap"):
			self.cmap = {}
		cmap = self.cmap
		for element in content:
			if not isinstance(element, tuple):
				continue
			name, attrs, content = element
			if name != "map":
				continue
			cmap[safeEval(attrs["code"])] = attrs["name"]
	def fromXML(self, name, attrs, content, ttFont):
		self.nameID = safeEval(attrs["nameID"])
		self.platformID = safeEval(attrs["platformID"])
		self.platEncID = safeEval(attrs["platEncID"])
		self.langID =  safeEval(attrs["langID"])
		s = strjoin(content).strip()
		encoding = self.getEncoding()
		if self.encodingIsUnicodeCompatible() or safeEval(attrs.get("unicode", "False")):
			self.string = s.encode(encoding)
		else:
			# This is the inverse of write8bit...
			self.string = s.encode("latin1")
Beispiel #12
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == 'version':
         self.version = float(safeEval(attrs['version']))
     elif name == 'lang':
         c = attrs['name']
         self.langs[c] = []
         for element in content:
             if not isinstance(element, tuple): continue
             tag, a, subcontent = element
             if tag == 'feature':
                 self.langs[c].append(
                     (grUtils.tag2num(a['fid']), int(safeEval(a['val']))))
Beispiel #13
0
	def fromXML(self, name, attrs, content, ttFont):
		self.language = safeEval(attrs["language"])
		if not hasattr(self, "cmap"):
			self.cmap = {}
		cmap = self.cmap

		for element in content:
			if not isinstance(element, tuple):
				continue
			nameMap, attrsMap, dummyContent = element
			if nameMap != "map":
				assert 0, "Unrecognized keyword in cmap subtable"
			cmap[safeEval(attrsMap["code"])] = attrsMap["name"]
 def fromXML(self, name, attrs, content, ttFont):
     if name == 'version':
         self.scheme = int(safeEval(attrs['compressionScheme']))
         self.version = float(safeEval(attrs['version']))
         self.compilerVersion = int(safeEval(attrs['compilerVersion']))
         return
     if name == 'silf':
         s = Silf()
         self.silfs.append(s)
         for element in content:
             if not isinstance(element, tuple): continue
             tag, attrs, subcontent = element
             s.fromXML(tag, attrs, subcontent, ttFont, self.version)
Beispiel #15
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == 'version':
         self.version = safeEval(attrs['value'])
     elif name == 'format':
         self.format = safeEval(attrs['value'])
     elif name in ('horizData', 'vertData'):
         trackData = TrackData()
         setattr(self, name, trackData)
         for element in content:
             if not isinstance(element, tuple):
                 continue
             name, attrs, content_ = element
             trackData.fromXML(name, attrs, content_, ttFont)
Beispiel #16
0
	def fromXML(self, name, attrs, content, ttFont):
		if name == "tableVersion":
			self.tableVersion = safeEval(attrs["version"])
			return
		if name[:12] != "cmap_format_":
			return
		if not hasattr(self, "tables"):
			self.tables = []
		format = safeEval(name[12:])
		table = CmapSubtable.newSubtable(format)
		table.platformID = safeEval(attrs["platformID"])
		table.platEncID = safeEval(attrs["platEncID"])
		table.fromXML(name, attrs, content, ttFont)
		self.tables.append(table)
    def fromXML(self, name, attrs, content, ttFont):
        assert (name == "NamedInstance")
        self.subfamilyNameID = safeEval(attrs["subfamilyNameID"])
        self.flags = safeEval(attrs.get("flags", "0"))
        if "postscriptNameID" in attrs:
            self.postscriptNameID = safeEval(attrs["postscriptNameID"])
        else:
            self.postscriptNameID = 0xFFFF

        for tag, elementAttrs, _ in filter(lambda t: type(t) is tuple,
                                           content):
            if tag == "coord":
                value = str2fl(elementAttrs["value"], 16)
                self.coordinates[elementAttrs["axis"]] = value
def _readRowImageData(bitmapObject, name, attrs, content, ttFont):
    bitDepth = safeEval(attrs['bitDepth'])
    metrics = SmallGlyphMetrics()
    metrics.width = safeEval(attrs['width'])
    metrics.height = safeEval(attrs['height'])

    dataRows = []
    for element in content:
        if not isinstance(element, tuple):
            continue
        name, attr, content = element
        # Chop off 'imagedata' from the tag to get just the option.
        if name == 'row':
            dataRows.append(deHexStr(attr['value']))
    bitmapObject.setRows(dataRows, bitDepth=bitDepth, metrics=metrics)
 def fromXML(self, name, attrs, content, ttFont):
     value = attrs["value"]
     if name in ("FFTimeStamp", "sourceCreated", "sourceModified"):
         value = timestampFromString(value)
     else:
         value = safeEval(value)
     setattr(self, name, value)
Beispiel #20
0
	def fromXML(self, name, attrs, content, ttFont):
		if name == "panose":
			self.panose = panose = Panose()
			for element in content:
				if isinstance(element, tuple):
					name, attrs, content = element
					panose.fromXML(name, attrs, content, ttFont)
		elif name in ("ulUnicodeRange1", "ulUnicodeRange2",
				"ulUnicodeRange3", "ulUnicodeRange4",
				"ulCodePageRange1", "ulCodePageRange2",
				"fsType", "fsSelection"):
			setattr(self, name, binary2num(attrs["value"]))
		elif name == "achVendID":
			setattr(self, name, safeEval("'''" + attrs["value"] + "'''"))
		else:
			setattr(self, name, safeEval(attrs["value"]))
Beispiel #21
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == "version":
         self.version = safeEval(attrs["value"])
         return
     if name != "kernsubtable":
         return
     if not hasattr(self, "kernTables"):
         self.kernTables = []
     format = safeEval(attrs["format"])
     if format not in kern_classes:
         subtable = KernTable_format_unkown(format)
     else:
         apple = self.version == 1.0
         subtable = kern_classes[format](apple)
     self.kernTables.append(subtable)
     subtable.fromXML(name, attrs, content, ttFont)
Beispiel #22
0
    def fromXML(self, name, attrs, content, ttFont):
        if name == "version":  # old COLR v0 API
            setattr(self, name, safeEval(attrs["value"]))
        elif name == "ColorGlyph":
            if not hasattr(self, "ColorLayers"):
                self.ColorLayers = {}
            glyphName = attrs["name"]
            for element in content:
                if isinstance(element, basestring):
                    continue
            layers = []
            for element in content:
                if isinstance(element, basestring):
                    continue
                layer = LayerRecord()
                layer.fromXML(element[0], element[1], element[2], ttFont)
                layers.append(layer)
            self.ColorLayers[glyphName] = layers
        else:  # new COLR v1 API
            from . import otTables

            if not hasattr(self, "table"):
                tableClass = getattr(otTables, self.tableTag)
                self.table = tableClass()
            self.table.fromXML(name, attrs, content, ttFont)
            self.table.populateDefaults()
Beispiel #23
0
    def fromXML(self, name, attrs, content, ttFont):
        # Read all the attributes. Even though the glyph indices are
        # recalculated, they are still read in case there needs to
        # be an immediate export of the data.
        self.imageFormat = safeEval(attrs['imageFormat'])
        self.firstGlyphIndex = safeEval(attrs['firstGlyphIndex'])
        self.lastGlyphIndex = safeEval(attrs['lastGlyphIndex'])

        self.readMetrics(name, attrs, content, ttFont)

        self.names = []
        for element in content:
            if not isinstance(element, tuple):
                continue
            name, attrs, content = element
            if name == 'glyphLoc':
                self.names.append(attrs['name'])
Beispiel #24
0
 def fromXML(self, name, attrs, content, ttFont):
     metricNames = set(sstruct.getformat(sbitLineMetricsFormat)[1])
     for element in content:
         if not isinstance(element, tuple):
             continue
         name, attrs, content = element
         if name in metricNames:
             vars(self)[name] = safeEval(attrs['value'])
 def fromXML(self, name, attrs, content, ttFont):
     if not hasattr(self, "tags"):
         self.tags = []
     if name == "LanguageTag":
         self.tags.append(attrs["tag"])
     elif "value" in attrs:
         value = safeEval(attrs["value"])
         setattr(self, name, value)
Beispiel #26
0
    def fromXML(self, name, attrs, content, ttFont):
        if name == 'header':
            self.version = safeEval(attrs['version'])
        elif name == 'strike':
            if not hasattr(self, 'strikes'):
                self.strikes = []
            strikeIndex = safeEval(attrs['index'])
            curStrike = Strike()
            curStrike.fromXML(name, attrs, content, ttFont, self)

            # Grow the strike array to the appropriate size. The XML format
            # allows for the strike index value to be out of order.
            if strikeIndex >= len(self.strikes):
                self.strikes += [None] * (strikeIndex + 1 - len(self.strikes))
            assert self.strikes[
                strikeIndex] is None, "Duplicate strike EBLC indices."
            self.strikes[strikeIndex] = curStrike
 def fromXML(self, name, attrs, content, ttFont, version=2.0):
     if name == 'version':
         self.ruleVersion = float(safeEval(attrs.get('ruleVersion', "0")))
     if name == 'info':
         getSimple(self, attrs, *attrs_info)
     elif name == 'passindexes':
         getSimple(self, attrs, *attrs_passindexes)
     elif name == 'contexts':
         getSimple(self, attrs, *attrs_contexts)
     elif name == 'attributes':
         getSimple(self, attrs, *attrs_attributes)
     elif name == 'justifications':
         for element in content:
             if not isinstance(element, tuple): continue
             (tag, attrs, subcontent) = element
             if tag == 'justify':
                 j = _Object()
                 for k, v in attrs.items():
                     setattr(j, k, int(v))
                 self.jLevels.append(j)
     elif name == 'critFeatures':
         self.critFeatures = []
         element = content_string(content)
         self.critFeatures.extend(map(int, element.split()))
     elif name == 'scriptTags':
         self.scriptTags = []
         element = content_string(content)
         for n in element.split():
             self.scriptTags.append(n)
     elif name == 'pseudoMap':
         self.pMap = {}
         for element in content:
             if not isinstance(element, tuple): continue
             (tag, attrs, subcontent) = element
             if tag == 'pseudo':
                 k = int(attrs['unicode'], 16)
                 v = attrs['pseudo']
             self.pMap[k] = v
     elif name == 'classes':
         self.classes = Classes()
         for element in content:
             if not isinstance(element, tuple): continue
             tag, attrs, subcontent = element
             self.classes.fromXML(tag, attrs, subcontent, ttFont, version)
     elif name == 'passes':
         for element in content:
             if not isinstance(element, tuple): continue
             tag, attrs, subcontent = element
             if tag == 'pass':
                 p = Pass()
                 for e in subcontent:
                     if not isinstance(e, tuple): continue
                     p.fromXML(e[0], e[1], e[2], ttFont, version)
                 self.passes.append(p)
Beispiel #28
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == "version":
         self.version = safeEval(attrs["value"])
     elif name == "ratRanges":
         if not hasattr(self, "ratRanges"):
             self.ratRanges = []
         for element in content:
             if not isinstance(element, tuple):
                 continue
             name, attrs, content = element
             if name == "ratRange":
                 if not hasattr(self, "numRatios"):
                     self.numRatios = 1
                 else:
                     self.numRatios += 1
                 ratio = {
                     "bCharSet": safeEval(attrs["bCharSet"]),
                     "xRatio": safeEval(attrs["xRatio"]),
                     "yStartRatio": safeEval(attrs["yStartRatio"]),
                     "yEndRatio": safeEval(attrs["yEndRatio"]),
                     "groupIndex": safeEval(attrs["groupIndex"])
                 }
                 self.ratRanges.append(ratio)
     elif name == "groups":
         if not hasattr(self, "groups"):
             self.groups = []
         for element in content:
             if not isinstance(element, tuple):
                 continue
             name, attrs, content = element
             if name == "group":
                 if not hasattr(self, "numRecs"):
                     self.numRecs = 1
                 else:
                     self.numRecs += 1
                 group = {}
                 for element in content:
                     if not isinstance(element, tuple):
                         continue
                     name, attrs, content = element
                     if name == "record":
                         yPelHeight = safeEval(attrs["yPelHeight"])
                         yMax = safeEval(attrs["yMax"])
                         yMin = safeEval(attrs["yMin"])
                         group[yPelHeight] = (yMax, yMin)
                 self.groups.append(group)
Beispiel #29
0
 def fromXML(self, name, attrs, content, ttFont):
     self.coverage = safeEval(attrs["coverage"])
     subtableFormat = safeEval(attrs["format"])
     if self.apple:
         if "tupleIndex" in attrs:
             self.tupleIndex = safeEval(attrs["tupleIndex"])
         else:
             # previous fontemon_blender_addon.fontTools versions didn't export tupleIndex
             log.warning(
                 "Apple kern subtable is missing 'tupleIndex' attribute")
             self.tupleIndex = None
     else:
         self.tupleIndex = None
     assert subtableFormat == self.format, "unsupported format"
     if not hasattr(self, "kernTable"):
         self.kernTable = {}
     for element in content:
         if not isinstance(element, tuple):
             continue
         name, attrs, content = element
         self.kernTable[(attrs["l"], attrs["r"])] = safeEval(attrs["v"])
 def fromXML(self, name, attrs, content, ttFont):
     metricNames = set(sstruct.getformat(self.__class__.binaryFormat)[1])
     for element in content:
         if not isinstance(element, tuple):
             continue
         name, attrs, content = element
         # Make sure this is a metric that is needed by GlyphMetrics.
         if name in metricNames:
             vars(self)[name] = safeEval(attrs['value'])
         else:
             log.warning("unknown name '%s' being ignored in %s.", name,
                         self.__class__.__name__)