Example #1
0
    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:
                    print("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
Example #2
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
Example #3
0
	def fromXML(self, name, attrs, content, ttFont):
		if name == "palette":
			self.paletteLabels.append(int(attrs.get("label", "0")))
			self.paletteTypes.append(int(attrs.get("type", "0")))
			palette = []
			for element in content:
				if isinstance(element, basestring):
					continue
				color = Color()
				color.fromXML(element[0], element[1], element[2], ttFont)
				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, 0)
				for i in range(self.numPaletteEntries)]
		elif "value" in attrs:
			value = safeEval(attrs["value"])
			setattr(self, name, value)
			if name == "numPaletteEntries":
				self.paletteEntryLabels = [0] * self.numPaletteEntries
Example #4
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)]
Example #5
0
	def fromXML(self, name, attrs, content, ttFont):
		self.format = safeEval(attrs["format"])
		self.length = safeEval(attrs["length"])
		self.numVarSelectorRecords = safeEval(attrs["numVarSelectorRecords"])
		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 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["name"]
			if gname == "None":
				gname = None
			try:
				uvsDict[uvs].append( [uv, gname])
			except KeyError:
				uvsDict[uvs] = [ [uv, gname] ]
Example #6
0
 def fromXML(self, name, attrs, content, ttFont):
     assert(name == "NamedInstance")
     self.flags = binary2num(attrs.get("flags", "0"))
     self.nameID = safeEval(attrs["nameID"])
     for tag, elementAttrs, _ in filter(lambda t: type(t) is tuple, content):
         if tag == "coord":
             self.coordinates[elementAttrs["axis"]] = safeEval(elementAttrs["value"])
Example #7
0
	def fromXML(self, xxx_todo_changeme, ttFont):
		(name, attrs, content) = xxx_todo_changeme
		if not hasattr(self, "metrics"):
			self.metrics = {}
		if name == "mtx":
			self.metrics[attrs["name"]] = [safeEval(attrs[self.advanceName]), 
					safeEval(attrs[self.sideBearingName])]
Example #8
0
	def fromXML(self, xxx_todo_changeme, ttFont):
		(name, attrs, content) = xxx_todo_changeme
		if name != "gaspRange":
			return
		if not hasattr(self, "gaspRange"):
			self.gaspRange = {}
		self.gaspRange[safeEval(attrs["rangeMaxPPEM"])] = safeEval(attrs["rangeGaspBehavior"])
Example #9
0
	def _startElementHandler(self, name, attrs):
		stackSize = self.stackSize
		self.stackSize = stackSize + 1
		if not stackSize:
			if name != "ttFont":
				raise TTXParseError("illegal root tag: %s" % name)
			sfntVersion = attrs.get("sfntVersion")
			if sfntVersion is not None:
				if len(sfntVersion) != 4:
					sfntVersion = safeEval('"' + sfntVersion + '"')
				self.ttFont.sfntVersion = sfntVersion
			self.contentStack.append([])
		elif stackSize == 1:
			subFile = attrs.get("src")
			if subFile is not None:
				if hasattr(self.file, 'name'):
					# if file has a name, get its parent directory
					dirname = os.path.dirname(self.file.name)
				else:
					# else fall back to using the current working directory
					dirname = os.getcwd()
				subFile = os.path.join(dirname, subFile)
				subReader = XMLReader(subFile, self.ttFont, self.progress, self.quiet)
				subReader.read()
				self.contentStack.append([])
				return
			tag = ttLib.xmlToTag(name)
			msg = "Parsing '%s' table..." % tag
			if self.progress:
				self.progress.setLabel(msg)
			elif self.ttFont.verbose:
				ttLib.debugmsg(msg)
			else:
				if not self.quiet:
					print(msg)
			if tag == "GlyphOrder":
				tableClass = ttLib.GlyphOrder
			elif "ERROR" in attrs or ('raw' in attrs and safeEval(attrs['raw'])):
				tableClass = DefaultTable
			else:
				tableClass = ttLib.getTableClass(tag)
				if tableClass is None:
					tableClass = DefaultTable
			if tag == 'loca' and tag in self.ttFont:
				# Special-case the 'loca' table as we need the
				#    original if the 'glyf' table isn't recompiled.
				self.currentTable = self.ttFont[tag]
			else:
				self.currentTable = tableClass(tag)
				self.ttFont[tag] = self.currentTable
			self.contentStack.append([])
		elif stackSize == 2:
			self.contentStack.append([])
			self.root = (name, attrs, self.contentStack[-1])
		else:
			l = []
			self.contentStack[-1].append((name, attrs, l))
			self.contentStack.append(l)
Example #10
0
	def fromXML(self, name, attrs, content, font):
		mapping = getattr(self, "mapping", None)
		if mapping is None:
			mapping = []
			self.mapping = mapping
		outer = safeEval(attrs['outer'])
		inner = safeEval(attrs['inner'])
		assert inner <= 0xFFFF
		mapping.append((outer << 16) | inner)
Example #11
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
Example #12
0
	def fromXML(self, name, attrs, content, ttFont):
		self.coverage = safeEval(attrs["coverage"])
		self.version = safeEval(attrs["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"])
Example #13
0
 def fromXML(self, name, attrs, content, ttFont):
     self.track = safeEval(attrs["value"])
     self.nameIndex = safeEval(attrs["nameIndex"])
     for element in content:
         if not isinstance(element, tuple):
             continue
         name, attrs, _ = element
         if name != "track":
             continue
         size = safeEval(attrs["size"])
         self[size] = safeEval(attrs["value"])
Example #14
0
	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)
Example #15
0
	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()
		if self.platformID == 0 or (self.platformID == 3 and self.platEncID in (0, 1)):
			self.string = s.encode("utf_16_be")
		else:
			# This is the inverse of write8bit...
			self.string = s.encode("latin1")
Example #16
0
	def fromXML(self, xxx_todo_changeme1, ttFont):
		(name, attrs, content) = xxx_todo_changeme1
		self.coverage = safeEval(attrs["coverage"])
		self.version = safeEval(attrs["format"])
		if not hasattr(self, "kernTable"):
			self.kernTable = {}
		for element in content:
			if type(element) != TupleType:
				continue
			name, attrs, content = element
			self.kernTable[(attrs["l"], attrs["r"])] = safeEval(attrs["v"])
Example #17
0
    def fromXML(self, name, attrs, content, ttFont):
        assert name == "NamedInstance"
        self.subfamilyNameID = safeEval(attrs["subfamilyNameID"])
        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":
                self.coordinates[elementAttrs["axis"]] = safeEval(elementAttrs["value"])
Example #18
0
	def fromXML(self, name, attrs, content, ttFont):
		self.track = safeEval(attrs['value'])
		self.nameIndex = safeEval(attrs['nameIndex'])
		for element in content:
			if not isinstance(element, tuple):
				continue
			name, attrs, _ = element
			if name != 'track':
				continue
			size = safeEval(attrs['size'])
			self[size] = safeEval(attrs['value'])
Example #19
0
	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")
Example #20
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"]
Example #21
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']))))
Example #22
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"]
Example #23
0
	def fromXML(self, name, attrs, content, font):
		mapping = getattr(self, "mapping", None)
		if mapping is None:
			mapping = {}
			self.mapping = mapping
		try:
			glyph = attrs['glyph']
		except: # https://github.com/fonttools/fonttools/commit/21cbab8ce9ded3356fef3745122da64dcaf314e9#commitcomment-27649836
			glyph = font.getGlyphOrder()[attrs['index']]
		outer = safeEval(attrs['outer'])
		inner = safeEval(attrs['inner'])
		assert inner <= 0xFFFF
		mapping[glyph] = (outer << 16) | inner
Example #24
0
	def fromXML(self, xxx_todo_changeme1, ttFont):
		(name, attrs, content) = xxx_todo_changeme1
		self.language = safeEval(attrs["language"])
		if not hasattr(self, "cmap"):
			self.cmap = {}
		cmap = self.cmap
		for element in content:
			if type(element) != TupleType:
				continue
			name, attrs, content = element
			if name != "map":
				continue
			cmap[safeEval(attrs["code"])] = attrs["name"]
Example #25
0
 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)
Example #26
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)
Example #27
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)
Example #28
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)
Example #29
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == "segment":
         axis = attrs["axis"]
         segment = self.segments[axis] = {}
         for element in content:
             if isinstance(element, tuple):
                 elementName, elementAttrs, _ = element
                 if elementName == "mapping":
                     fromValue = safeEval(elementAttrs["from"])
                     toValue = safeEval(elementAttrs["to"])
                     if fromValue in segment:
                         log.warning("duplicate entry for %s in axis '%s'",
                                     fromValue, axis)
                     segment[fromValue] = toValue
Example #30
0
	def fromXML(self, name, attrs, _content):
		if name == "coord":
			axis = attrs["axis"]
			value = float(attrs["value"])
			defaultMinValue = min(value, 0.0)  # -0.3 --> -0.3; 0.7 --> 0.0
			defaultMaxValue = max(value, 0.0)  # -0.3 -->  0.0; 0.7 --> 0.7
			minValue = float(attrs.get("min", defaultMinValue))
			maxValue = float(attrs.get("max", defaultMaxValue))
			self.axes[axis] = (minValue, value, maxValue)
		elif name == "delta":
			point = safeEval(attrs["pt"])
			x = safeEval(attrs["x"])
			y = safeEval(attrs["y"])
			self.coordinates[point] = (x, y)
 def fromXML(self, name, attrs, content, ttFont):
     if name == "ref":
         # glyph is a "dupe", i.e. a reference to another glyph's image data.
         # in this case imageData contains the glyph id of the reference glyph
         # get glyph id from glyphname
         self.imageData = struct.pack(
             ">H",
             ttFont.getGlyphID(safeEval("'''" + attrs["glyphname"] +
                                        "'''")))
     elif name == "hexdata":
         self.imageData = readHex(content)
     else:
         from fontTools import ttLib
         raise ttLib.TTLibError("can't handle '%s' element" % name)
Example #32
0
 def xmlRead(self, attrs, content, font):
     if "empty" in attrs and safeEval(attrs["empty"]):
         return None
     table = self.tableClass()
     Format = attrs.get("Format")
     if Format is not None:
         table.Format = int(Format)
     for element in content:
         if isinstance(element, tuple):
             name, attrs, content = element
             table.fromXML(name, attrs, content, font)
         else:
             pass
     return table
Example #33
0
def _readBitwiseImageData(bitmapObject, name, attrs, content, ttFont):
    bitDepth = safeEval(attrs['bitDepth'])
    metrics = SmallGlyphMetrics()
    metrics.width = safeEval(attrs['width'])
    metrics.height = safeEval(attrs['height'])

    # A dict for mapping from ASCII to binary. All characters are considered
    # a '1' except space, period and '0' which maps to '0'.
    binaryConv = {' ': '0', '.': '0', '0': '0'}

    dataRows = []
    for element in content:
        if not isinstance(element, tuple):
            continue
        name, attr, content = element
        if name == 'row':
            mapParams = zip(attr['value'], itertools.repeat('1'))
            rowData = strjoin(itertools.starmap(binaryConv.get, mapParams))
            dataRows.append(_binary2data(rowData))

    bitmapObject.setRows(dataRows,
                         bitDepth=bitDepth,
                         metrics=metrics,
                         reverseBytes=True)
Example #34
0
 def fromXML(self, name, attrs, content, ttFont, locator):
     for element in content:
         if not isinstance(element, tuple):
             continue
         name, attrs, content = element
         if name == 'bitmapSizeTable':
             self.bitmapSizeTable.fromXML(name, attrs, content, ttFont)
         elif name.startswith(_indexSubTableSubclassPrefix):
             indexFormat = safeEval(
                 name[len(_indexSubTableSubclassPrefix):])
             indexFormatClass = locator.getIndexFormatClass(indexFormat)
             indexSubTable = indexFormatClass(None, None)
             indexSubTable.indexFormat = indexFormat
             indexSubTable.fromXML(name, attrs, content, ttFont)
             self.indexSubTables.append(indexSubTable)
Example #35
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == "GlyphRecord":
         if not hasattr(self, "glyphRecords"):
             self.glyphRecords = []
         glyphRec = GlyphRecord()
         self.glyphRecords.append(glyphRec)
         for element in content:
             if isinstance(element, basestring):
                 continue
             name, attrs, content = element
             glyphRec.fromXML(name, attrs, content, ttFont)
         glyphRec.offset = -1
         glyphRec.nMetaEntry = len(glyphRec.stringRecs)
     else:
         setattr(self, name, safeEval(attrs["value"]))
Example #36
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == "version":
         setattr(self, name, safeEval(attrs["value"]))
     elif name == "flags":
         setattr(self, name, binary2num(attrs["value"]))
     elif name == "strike":
         current_strike = Strike()
         for element in content:
             if isinstance(element, tuple):
                 name, attrs, content = element
                 current_strike.fromXML(name, attrs, content, ttFont)
         self.strikes[current_strike.ppem] = current_strike
     else:
         from fontTools import ttLib
         raise ttLib.TTLibError("can't handle '%s' element" % name)
Example #37
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == "version":
         self.version = safeEval(attrs["value"])
     elif name == "reserved":
         self.reserved = safeEval(attrs["value"])
     elif name == "glyphVariations":
         if not hasattr(self, "variations"):
             self.variations = {}
         glyphName = attrs["glyph"]
         glyph = ttFont["glyf"][glyphName]
         numPointsInGlyph = self.getNumPoints_(glyph)
         glyphVariations = []
         for element in content:
             if isinstance(element, tuple):
                 name, attrs, content = element
                 if name == "tuple":
                     gvar = TupleVariation({}, [None] * numPointsInGlyph)
                     glyphVariations.append(gvar)
                     for tupleElement in content:
                         if isinstance(tupleElement, tuple):
                             tupleName, tupleAttrs, tupleContent = tupleElement
                             gvar.fromXML(tupleName, tupleAttrs,
                                          tupleContent)
         self.variations[glyphName] = glyphVariations
Example #38
0
	def fromXML(self, xxx_todo_changeme1, ttFont):
		(name, attrs, content) = xxx_todo_changeme1
		if name == "StringRecord":
			stringRec = StringRecord()
			self.stringRecs.append(stringRec)
			for element in content:
				if type(element) is str:
					continue
				stringRec.fromXML(element, ttFont)
			stringRec.stringLen = len(stringRec.string)
		else:			
			value = attrs["value"]
			try:
				value = safeEval(value)
			except OverflowError:
				value = int(value)
			setattr(self, name, value)
Example #39
0
	def fromXML(self, name, attrs, content, font):
		self.__init__()
		content = [t for t in content if isinstance(t, tuple)]
		for eltName, eltAttrs, eltContent in content:
			if eltName == "NewState":
				self.NewState = safeEval(eltAttrs["value"])
			elif eltName == "Flags":
				for flag in eltAttrs["value"].split(","):
					self._setFlag(flag.strip())
			elif eltName == "CurrentInsertionAction":
				self.CurrentInsertionAction.append(
					eltAttrs["glyph"])
			elif eltName == "MarkedInsertionAction":
				self.MarkedInsertionAction.append(
					eltAttrs["glyph"])
			else:
				assert False, eltName
Example #40
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == "GMAPRecord":
         if not hasattr(self, "gmapRecords"):
             self.gmapRecords = []
         gmapRecord = GMAPRecord()
         self.gmapRecords.append(gmapRecord)
         for element in content:
             if isinstance(element, str):
                 continue
             name, attrs, content = element
             gmapRecord.fromXML(name, attrs, content, ttFont)
     else:
         value = attrs["value"]
         if name == "PSFontName":
             self.psFontName = value
         else:
             setattr(self, name, safeEval(value))
Example #41
0
class FixedSizeIndexSubTableMixin:
    def writeMetrics(self, writer, ttFont):
        writer.simpletag('imageSize', value=self.imageSize)
        writer.newline()
        self.metrics.toXML(writer, ttFont)

    def readMetrics(self, (name, attrs, content), ttFont):
        for element in content:
            if type(element) != TupleType:
                continue
            name, attrs, content = element
            if name == 'imageSize':
                self.imageSize = safeEval(attrs['value'])
            elif name == BigGlyphMetrics.__name__:
                self.metrics = BigGlyphMetrics()
                self.metrics.fromXML(element, ttFont)
            elif name == SmallGlyphMetrics.__name__:
                print "Warning: SmallGlyphMetrics being ignored in format %d." % self.indexFormat
Example #42
0
class SbitLineMetrics:
    def toXML(self, name, writer, ttFont):
        writer.begintag('sbitLineMetrics', [('direction', name)])
        writer.newline()
        for metricName in sstruct.getformat(sbitLineMetricsFormat)[1]:
            writer.simpletag(metricName, value=getattr(self, metricName))
            writer.newline()
        writer.endtag('sbitLineMetrics')
        writer.newline()

    def fromXML(self, (name, attrs, content), ttFont):
        metricNames = set(sstruct.getformat(sbitLineMetricsFormat)[1])
        for element in content:
            if type(element) != TupleType:
                continue
            name, attrs, content = element
            if name in metricNames:
                vars(self)[name] = safeEval(attrs['value'])
	def fromXML(self, name, attrs, content, ttFont):
		# Create a lookup for all the simple names that make sense to
		# bitmap size table. Only read the information from these names.
		dataNames = set(self._getXMLMetricNames())
		for element in content:
			if not isinstance(element, tuple):
				continue
			name, attrs, content = element
			if name == 'sbitLineMetrics':
				direction = attrs['direction']
				assert direction in ('hori', 'vert'), "SbitLineMetrics direction specified invalid."
				metricObj = SbitLineMetrics()
				metricObj.fromXML(name, attrs, content, ttFont)
				vars(self)[direction] = metricObj
			elif name in dataNames:
				vars(self)[name] = safeEval(attrs['value'])
			else:
				log.warning("unknown name '%s' being ignored in BitmapSizeTable.", name)
Example #44
0
 def fromXML(self, xxx_todo_changeme, ttFont):
     (name, attrs, content) = xxx_todo_changeme
     if not hasattr(self, "VOriginRecords"):
         self.VOriginRecords = {}
     self.getGlyphName = ttFont.getGlyphName  # for use in get/set item functions, for access by GID
     if name == "VOriginRecord":
         for element in content:
             if type(element) is str:
                 continue
         vOriginRec = VOriginRecord()
         for element in content:
             if type(element) is str:
                 continue
             vOriginRec.fromXML(element, ttFont)
         self.VOriginRecords[vOriginRec.glyphName] = vOriginRec.vOrigin
     elif "value" in attrs:
         value = safeEval(attrs["value"])
         setattr(self, name, value)
 def fromXML(self, name, attrs, content, ttFont):
     if not hasattr(self, "palettes"):
         self.palettes = []
     if name == "palette":
         palette = []
         for element in content:
             if isinstance(element, basestring):
                 continue
         palette = []
         for element in content:
             if isinstance(element, basestring):
                 continue
             color = Color()
             color.fromXML(element[0], element[1], element[2], ttFont)
             palette.append(color)
         self.palettes.append(palette)
     elif "value" in attrs:
         value = safeEval(attrs["value"])
         setattr(self, name, value)
Example #46
0
 def fromXML(self, name, attrs, content, ttFont):
     if not hasattr(self, "ColorLayers"):
         self.ColorLayers = {}
     self.getGlyphName = ttFont.getGlyphName  # for use in get/set item functions, for access by GID
     if name == "ColorGlyph":
         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)
         operator.setitem(self, glyphName, layers)
     elif "value" in attrs:
         setattr(self, name, safeEval(attrs["value"]))
Example #47
0
    def xmlRead(self, attrs, content, font):
        if "empty" in attrs and safeEval(attrs["empty"]):
            return None
        table = self.tableClass()
        Format = attrs.get("Format")
        if Format is not None:
            table.Format = int(Format)

        noPostRead = not hasattr(table, 'postRead')
        if noPostRead:
            # TODO Cache table.hasPropagated.
            cleanPropagation = False
            for conv in table.getConverters():
                if conv.isPropagated:
                    cleanPropagation = True
                    if not hasattr(font, '_propagator'):
                        font._propagator = {}
                    propagator = font._propagator
                    assert conv.name not in propagator, (conv.name, propagator)
                    setattr(table, conv.name, None)
                    propagator[conv.name] = CountReference(
                        table.__dict__, conv.name)

        for element in content:
            if isinstance(element, tuple):
                name, attrs, content = element
                table.fromXML(name, attrs, content, font)
            else:
                pass

        table.populateDefaults(propagator=getattr(font, '_propagator', None))

        if noPostRead:
            if cleanPropagation:
                for conv in table.getConverters():
                    if conv.isPropagated:
                        propagator = font._propagator
                        del propagator[conv.name]
                        if not propagator:
                            del font._propagator

        return table
Example #48
0
class BitmapSizeTable:

    # Returns all the simple metric names that bitmap size table
    # cares about in terms of XML creation.
    def _getXMLMetricNames(self):
        dataNames = sstruct.getformat(bitmapSizeTableFormatPart1)[1]
        dataNames = dataNames + sstruct.getformat(
            bitmapSizeTableFormatPart2)[1]
        # Skip the first 3 data names because they are byte offsets and counts.
        return dataNames[3:]

    def toXML(self, writer, ttFont):
        writer.begintag('bitmapSizeTable')
        writer.newline()
        for metric in ('hori', 'vert'):
            getattr(self, metric).toXML(metric, writer, ttFont)
        for metricName in self._getXMLMetricNames():
            writer.simpletag(metricName, value=getattr(self, metricName))
            writer.newline()
        writer.endtag('bitmapSizeTable')
        writer.newline()

    def fromXML(self, (name, attrs, content), ttFont):
        # Create a lookup for all the simple names that make sense to
        # bitmap size table. Only read the information from these names.
        dataNames = set(self._getXMLMetricNames())
        for element in content:
            if type(element) != TupleType:
                continue
            name, attrs, content = element
            if name == 'sbitLineMetrics':
                direction = attrs['direction']
                assert direction in (
                    'hori',
                    'vert'), "SbitLineMetrics direction specified invalid."
                metricObj = SbitLineMetrics()
                metricObj.fromXML(element, ttFont)
                vars(self)[direction] = metricObj
            elif name in dataNames:
                vars(self)[name] = safeEval(attrs['value'])
            else:
                print "Warning: unknown name '%s' being ignored in BitmapSizeTable." % name
Example #49
0
	def fromXML(self, xxx_todo_changeme, ttFont):
		(name, attrs, content) = xxx_todo_changeme
		if name == "GlyphRecord":
			if not hasattr(self, "glyphRecords"):
				self.glyphRecords = []
			glyphRec = GlyphRecord()
			self.glyphRecords.append(glyphRec)
			for element in content:
				if type(element) is str:
					continue
				glyphRec.fromXML(element, ttFont)
			glyphRec.offset = -1
			glyphRec.nMetaEntry = len(glyphRec.stringRecs)
		else:			
			value = attrs["value"]
			try:
				value = safeEval(value)
			except OverflowError:
				value = int(value)
			setattr(self, name, value)
Example #50
0
	def fromXML(self, name, attrs, content, ttFont):
		if name != "TTGlyph":
			return
		if not hasattr(self, "glyphs"):
			self.glyphs = {}
		if not hasattr(self, "glyphOrder"):
			self.glyphOrder = ttFont.getGlyphOrder()
		glyphName = attrs["name"]
		log.debug("unpacking glyph '%s'", glyphName)
		glyph = Glyph()
		for attr in ['xMin', 'yMin', 'xMax', 'yMax']:
			setattr(glyph, attr, safeEval(attrs.get(attr, '0')))
		self.glyphs[glyphName] = glyph
		for element in content:
			if not isinstance(element, tuple):
				continue
			name, attrs, content = element
			glyph.fromXML(name, attrs, content, ttFont)
		if not ttFont.recalcBBoxes:
			glyph.compact(self, 0)
Example #51
0
 def fromXML(self, name, attrs, content, ttFont, version=2.0):
     if name == 'linearClasses':
         for element in content:
             if not isinstance(element, tuple): continue
             tag, attrs, subcontent = element
             if tag == 'linear':
                 l = content_string(subcontent).split()
                 self.linear.append(l)
     elif name == 'nonLinearClasses':
         for element in content:
             if not isinstance(element, tuple): continue
             tag, attrs, subcontent = element
             if tag == 'nonLinear':
                 l = {}
                 for e in subcontent:
                     if not isinstance(e, tuple): continue
                     tag, attrs, subsubcontent = e
                     if tag == 'map':
                         l[attrs['glyph']] = int(safeEval(attrs['index']))
                 self.nonLinear.append(l)
Example #52
0
	def fromXML(self, name, attrs, content, ttFont):
		if name == "GMAPs":
			if not hasattr(self, "GMAPs"):
				self.GMAPs = []
			for element in content:
				if isinstance(element, basestring):
					continue
				itemName, itemAttrs, itemContent = element
				if itemName == "hexdata":
					self.GMAPs.append(readHex(itemContent))
		elif name == "glyphlets":
			if not hasattr(self, "glyphlets"):
				self.glyphlets = []
			for element in content:
				if isinstance(element, basestring):
					continue
				itemName, itemAttrs, itemContent = element
				if itemName == "hexdata":
					self.glyphlets.append(readHex(itemContent))
		else:
			setattr(self, name, safeEval(attrs["value"]))
Example #53
0
 def fromXML(self, name, attrs, content, ttFont):
     if name not in ("psNames", "extraNames", "hexdata"):
         setattr(self, name, safeEval(attrs["value"]))
     elif name == "psNames":
         self.mapping = {}
         for element in content:
             if not isinstance(element, tuple):
                 continue
             name, attrs, content = element
             if name == "psName":
                 self.mapping[attrs["name"]] = attrs["psName"]
     elif name == "extraNames":
         self.extraNames = []
         for element in content:
             if not isinstance(element, tuple):
                 continue
             name, attrs, content = element
             if name == "psName":
                 self.extraNames.append(attrs["name"])
     else:
         self.data = readHex(content)
Example #54
0
class LayerRecord:
    def __init__(self, name=None, colorID=None):
        self.name = name
        self.colorID = colorID

    def toXML(self, writer, ttFont):
        writer.simpletag("layer", name=self.name, colorID=self.colorID)
        writer.newline()

    def fromXML(self, (eltname, attrs, content), ttFont):
        for (name, value) in attrs.items():
            if name == "name":
                if type(value) == IntType:
                    value = ttFont.getGlyphName(value)
                setattr(self, name, value)
            else:
                try:
                    value = safeEval(value)
                except OverflowError:
                    value = long(value)
                setattr(self, name, value)
Example #55
0
class EbdtComponent:
    def toXML(self, writer, ttFont):
        writer.begintag('ebdtComponent', [('name', self.name)])
        writer.newline()
        for componentName in sstruct.getformat(ebdtComponentFormat)[1][1:]:
            writer.simpletag(componentName, value=getattr(self, componentName))
            writer.newline()
        writer.endtag('ebdtComponent')
        writer.newline()

    def fromXML(self, (name, attrs, content), ttFont):
        self.name = attrs['name']
        componentNames = set(sstruct.getformat(ebdtComponentFormat)[1][1:])
        for element in content:
            if type(element) != TupleType:
                continue
            name, attrs, content = element
            if name in componentNames:
                vars(self)[name] = safeEval(attrs['value'])
            else:
                print "Warning: unknown name '%s' being ignored by EbdtComponent." % name
Example #56
0
 def fromXML(self, xxx_todo_changeme1, ttFont):
     (name, attrs, content) = xxx_todo_changeme1
     if name == "GMAPRecord":
         if not hasattr(self, "gmapRecords"):
             self.gmapRecords = []
         gmapRecord = GMAPRecord()
         self.gmapRecords.append(gmapRecord)
         for element in content:
             if type(element) is str:
                 continue
             gmapRecord.fromXML(element, ttFont)
     else:
         value = attrs["value"]
         if name == "PSFontName":
             self.psFontName = value
         else:
             try:
                 value = safeEval(value)
             except OverflowError:
                 value = int(value)
             setattr(self, name, value)
Example #57
0
	def fromXML(self, xxx_todo_changeme, ttFont):
		(name, attrs, content) = xxx_todo_changeme
		if name != "TTGlyph":
			return
		if not hasattr(self, "glyphs"):
			self.glyphs = {}
		if not hasattr(self, "glyphOrder"):
			self.glyphOrder = ttFont.getGlyphOrder()
		glyphName = attrs["name"]
		if ttFont.verbose:
			ttLib.debugmsg("unpacking glyph '%s'" % glyphName)
		glyph = Glyph()
		for attr in ['xMin', 'yMin', 'xMax', 'yMax']:
			setattr(glyph, attr, safeEval(attrs.get(attr, '0')))
		self.glyphs[glyphName] = glyph
		for element in content:
			if type(element) is not tuple:
				continue
			glyph.fromXML(element, ttFont)
		if not ttFont.recalcBBoxes:
			glyph.compact(self, 0)
Example #58
0
class BitmapGlyphMetrics:
    def toXML(self, writer, ttFont):
        writer.begintag(self.__class__.__name__)
        writer.newline()
        for metricName in sstruct.getformat(self.__class__.binaryFormat)[1]:
            writer.simpletag(metricName, value=getattr(self, metricName))
            writer.newline()
        writer.endtag(self.__class__.__name__)
        writer.newline()

    def fromXML(self, (name, attrs, content), ttFont):
        metricNames = set(sstruct.getformat(self.__class__.binaryFormat)[1])
        for element in content:
            if type(element) != TupleType:
                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:
                print "Warning: unknown name '%s' being ignored in %s." % name, self.__class__.__name__
Example #59
0
class table_L_T_S_H_(DefaultTable.DefaultTable):
    def decompile(self, data, ttFont):
        version, numGlyphs = struct.unpack(">HH", data[:4])
        data = data[4:]
        assert version == 0, "unknown version: %s" % version
        assert (len(data) %
                numGlyphs) < 4, "numGlyphs doesn't match data length"
        # ouch: the assertion is not true in Chicago!
        #assert numGlyphs == ttFont['maxp'].numGlyphs
        yPels = array.array("B")
        yPels.fromstring(data)
        self.yPels = {}
        for i in range(numGlyphs):
            self.yPels[ttFont.getGlyphName(i)] = yPels[i]

    def compile(self, ttFont):
        version = 0
        names = self.yPels.keys()
        numGlyphs = len(names)
        yPels = [0] * numGlyphs
        # ouch: the assertion is not true in Chicago!
        #assert len(self.yPels) == ttFont['maxp'].numGlyphs == numGlyphs
        for name in names:
            yPels[ttFont.getGlyphID(name)] = self.yPels[name]
        yPels = array.array("B", yPels)
        return struct.pack(">HH", version, numGlyphs) + yPels.tostring()

    def toXML(self, writer, ttFont):
        names = self.yPels.keys()
        names.sort()
        for name in names:
            writer.simpletag("yPel", name=name, value=self.yPels[name])
            writer.newline()

    def fromXML(self, (name, attrs, content), ttFont):
        if not hasattr(self, "yPels"):
            self.yPels = {}
        if name <> "yPel":
            return  # ignore unknown tags
        self.yPels[attrs["name"]] = safeEval(attrs["value"])
Example #60
0
 def fromXML(self, xxx_todo_changeme, ttFont):
     (name, attrs, content) = xxx_todo_changeme
     if name not in ("psNames", "extraNames", "hexdata"):
         setattr(self, name, safeEval(attrs["value"]))
     elif name == "psNames":
         self.mapping = {}
         for element in content:
             if type(element) is not tuple:
                 continue
             name, attrs, content = element
             if name == "psName":
                 self.mapping[attrs["name"]] = attrs["psName"]
     elif name == "extraNames":
         self.extraNames = []
         for element in content:
             if type(element) is not tuple:
                 continue
             name, attrs, content = element
             if name == "psName":
                 self.extraNames.append(attrs["name"])
     else:
         self.data = readHex(content)