Пример #1
0
 def compile(self, ttFont):
     try:
         max_location = max(self.locations)
     except AttributeError:
         self.set([])
         max_location = 0
     if 'glyf' in ttFont and hasattr(ttFont['glyf'], 'indexFormat'):
         # copile loca using the indexFormat specified in the WOFF2 glyf table
         indexFormat = ttFont['glyf'].indexFormat
         if indexFormat == 0:
             if max_location >= 0x20000:
                 raise TTLibError(
                     "indexFormat is 0 but local offsets > 0x20000")
             if not all(l % 2 == 0 for l in self.locations):
                 raise TTLibError(
                     "indexFormat is 0 but local offsets not multiples of 2"
                 )
             locations = array.array("H")
             for i in range(len(self.locations)):
                 locations.append(self.locations[i] // 2)
         else:
             locations = array.array("I", self.locations)
         if sys.byteorder != "big":
             locations.byteswap()
         data = locations.tostring()
     else:
         # use the most compact indexFormat given the current glyph offsets
         data = super(WOFF2LocaTable, self).compile(ttFont)
     return data
Пример #2
0
    def __init__(self, file, checkChecksums=1, fontNumber=-1):
        self.file = file
        self.checkChecksums = checkChecksums

        self.flavor = None
        self.flavorData = None
        self.DirectoryEntry = SFNTDirectoryEntry
        self.file.seek(0)
        self.sfntVersion = self.file.read(4)
        self.file.seek(0)
        if self.sfntVersion == b"ttcf":
            header = readTTCHeader(self.file)
            numFonts = header.numFonts
            if not 0 <= fontNumber < numFonts:
                raise TTLibError(
                    "specify a font number between 0 and %d (inclusive)" %
                    (numFonts - 1))
            self.numFonts = numFonts
            self.file.seek(header.offsetTable[fontNumber])
            data = self.file.read(sfntDirectorySize)
            if len(data) != sfntDirectorySize:
                raise TTLibError("Not a Font Collection (not enough data)")
            sstruct.unpack(sfntDirectoryFormat, data, self)
        elif self.sfntVersion == b"wOFF":
            self.flavor = "woff"
            self.DirectoryEntry = WOFFDirectoryEntry
            data = self.file.read(woffDirectorySize)
            if len(data) != woffDirectorySize:
                raise TTLibError("Not a WOFF font (not enough data)")
            sstruct.unpack(woffDirectoryFormat, data, self)
        else:
            data = self.file.read(sfntDirectorySize)
            if len(data) != sfntDirectorySize:
                raise TTLibError(
                    "Not a TrueType or OpenType font (not enough data)")
            sstruct.unpack(sfntDirectoryFormat, data, self)
        self.sfntVersion = Tag(self.sfntVersion)

        if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"):
            raise TTLibError(
                "Not a TrueType or OpenType font (bad sfntVersion)")
        tables = {}
        for i in range(self.numTables):
            entry = self.DirectoryEntry()
            entry.fromFile(self.file)
            tag = Tag(entry.tag)
            tables[tag] = entry
        self.tables = OrderedDict(
            sorted(tables.items(), key=lambda i: i[1].offset))

        # Load flavor data if any
        if self.flavor == "woff":
            self.flavorData = WOFFFlavorData(self)
Пример #3
0
    def reconstruct(self, data, ttFont):
        """ Decompile transformed 'glyf' data. """
        inputDataSize = len(data)

        if inputDataSize < woff2GlyfTableFormatSize:
            raise TTLibError("not enough 'glyf' data")
        dummy, data = sstruct.unpack2(woff2GlyfTableFormat, data, self)
        offset = woff2GlyfTableFormatSize

        for stream in self.subStreams:
            size = getattr(self, stream + 'Size')
            setattr(self, stream, data[:size])
            data = data[size:]
            offset += size

        if offset != inputDataSize:
            raise TTLibError(
                "incorrect size of transformed 'glyf' table: expected %d, received %d bytes"
                % (offset, inputDataSize))

        bboxBitmapSize = ((self.numGlyphs + 31) >> 5) << 2
        bboxBitmap = self.bboxStream[:bboxBitmapSize]
        self.bboxBitmap = array.array('B', bboxBitmap)
        self.bboxStream = self.bboxStream[bboxBitmapSize:]

        self.nContourStream = array.array("h", self.nContourStream)
        if sys.byteorder != "big":
            self.nContourStream.byteswap()
        assert len(self.nContourStream) == self.numGlyphs

        if 'head' in ttFont:
            ttFont['head'].indexToLocFormat = self.indexFormat
        try:
            self.glyphOrder = ttFont.getGlyphOrder()
        except:
            self.glyphOrder = None
        if self.glyphOrder is None:
            self.glyphOrder = [".notdef"]
            self.glyphOrder.extend(
                ["glyph%.5d" % i for i in range(1, self.numGlyphs)])
        else:
            if len(self.glyphOrder) != self.numGlyphs:
                raise TTLibError(
                    "incorrect glyphOrder: expected %d glyphs, found %d" %
                    (len(self.glyphOrder), self.numGlyphs))

        glyphs = self.glyphs = {}
        for glyphID, glyphName in enumerate(self.glyphOrder):
            glyph = self._decodeGlyph(glyphID)
            glyphs[glyphName] = glyph
Пример #4
0
def readTTCHeader(file):
	file.seek(0)
	data = file.read(ttcHeaderSize)
	if len(data) != ttcHeaderSize:
		raise TTLibError("Not a Font Collection (not enough data)")
	self = SimpleNamespace()
	sstruct.unpack(ttcHeaderFormat, data, self)
	if self.TTCTag != "ttcf":
		raise TTLibError("Not a Font Collection")
	assert self.Version == 0x00010000 or self.Version == 0x00020000, "unrecognized TTC version 0x%08x" % self.Version
	self.offsetTable = struct.unpack(">%dL" % self.numFonts, file.read(self.numFonts * 4))
	if self.Version == 0x00020000:
		pass # ignoring version 2.0 signatures
	return self
Пример #5
0
	def close(self):
		""" All tags must have been specified. Now write the table data and directory.
		"""
		if len(self.tables) != self.numTables:
			raise TTLibError("wrong number of tables; expected %d, found %d" % (self.numTables, len(self.tables)))

		if self.sfntVersion in ("\x00\x01\x00\x00", "true"):
			isTrueType = True
		elif self.sfntVersion == "OTTO":
			isTrueType = False
		else:
			raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")

		# The WOFF2 spec no longer requires the glyph offsets to be 4-byte aligned.
		# However, the reference WOFF2 implementation still fails to reconstruct
		# 'unpadded' glyf tables, therefore we need to 'normalise' them.
		# See:
		# https://github.com/khaledhosny/ots/issues/60
		# https://github.com/google/woff2/issues/15
		if (
			isTrueType
			and "glyf" in self.flavorData.transformedTables
			and "glyf" in self.tables
		):
			self._normaliseGlyfAndLoca(padding=4)
		self._setHeadTransformFlag()

		# To pass the legacy OpenType Sanitiser currently included in browsers,
		# we must sort the table directory and data alphabetically by tag.
		# See:
		# https://github.com/google/woff2/pull/3
		# https://lists.w3.org/Archives/Public/public-webfonts-wg/2015Mar/0000.html
		# TODO(user): remove to match spec once browsers are on newer OTS
		self.tables = OrderedDict(sorted(self.tables.items()))

		self.totalSfntSize = self._calcSFNTChecksumsLengthsAndOffsets()

		fontData = self._transformTables()
		compressedFont = brotli.compress(fontData, mode=brotli.MODE_FONT)

		self.totalCompressedSize = len(compressedFont)
		self.length = self._calcTotalSize()
		self.majorVersion, self.minorVersion = self._getVersion()
		self.reserved = 0

		directory = self._packTableDirectory()
		self.file.seek(0)
		self.file.write(pad(directory + compressedFont, size=4))
		self._writeFlavorData()
Пример #6
0
    def __init__(self, file, checkChecksums=1, fontNumber=-1):
        if not haveBrotli:
            print(
                'The WOFF2 decoder requires the Brotli Python extension, available at:\n'
                'https://github.com/google/brotli',
                file=sys.stderr)
            raise ImportError("No module named brotli")

        self.file = file

        signature = Tag(self.file.read(4))
        if signature != b"wOF2":
            raise TTLibError("Not a WOFF2 font (bad signature)")

        self.file.seek(0)
        self.DirectoryEntry = WOFF2DirectoryEntry
        data = self.file.read(woff2DirectorySize)
        if len(data) != woff2DirectorySize:
            raise TTLibError('Not a WOFF2 font (not enough data)')
        sstruct.unpack(woff2DirectoryFormat, data, self)

        self.tables = OrderedDict()
        offset = 0
        for i in range(self.numTables):
            entry = self.DirectoryEntry()
            entry.fromFile(self.file)
            tag = Tag(entry.tag)
            self.tables[tag] = entry
            entry.offset = offset
            offset += entry.length

        totalUncompressedSize = offset
        compressedData = self.file.read(self.totalCompressedSize)
        decompressedData = brotli.decompress(compressedData)
        if len(decompressedData) != totalUncompressedSize:
            raise TTLibError(
                'unexpected size for decompressed font data: expected %d, found %d'
                % (totalUncompressedSize, len(decompressedData)))
        self.transformBuffer = BytesIO(decompressedData)

        self.file.seek(0, 2)
        if self.length != self.file.tell():
            raise TTLibError(
                "reported 'length' doesn't match the actual file size")

        self.flavorData = WOFF2FlavorData(self)

        # make empty TTFont to store data while reconstructing tables
        self.ttFont = TTFont(recalcBBoxes=False, recalcTimestamp=False)
Пример #7
0
    def getGlyphSet(self, preferCFF=True):
        """Return a generic GlyphSet, which is a dict-like object
		mapping glyph names to glyph objects. The returned glyph objects
		have a .draw() method that supports the Pen protocol, and will
		have an attribute named 'width'.

		If the font is CFF-based, the outlines will be taken from the 'CFF ' or
		'CFF2' tables. Otherwise the outlines will be taken from the 'glyf' table.
		If the font contains both a 'CFF '/'CFF2' and a 'glyf' table, you can use
		the 'preferCFF' argument to specify which one should be taken. If the
		font contains both a 'CFF ' and a 'CFF2' table, the latter is taken.
		"""
        glyphs = None
        if (preferCFF and any(tb in self for tb in ["CFF ", "CFF2"])
                or ("glyf" not in self and any(tb in self
                                               for tb in ["CFF ", "CFF2"]))):
            table_tag = "CFF2" if "CFF2" in self else "CFF "
            glyphs = _TTGlyphSet(
                self,
                list(self[table_tag].cff.values())[0].CharStrings, _TTGlyphCFF)

        if glyphs is None and "glyf" in self:
            glyphs = _TTGlyphSet(self, self["glyf"], _TTGlyphGlyf)

        if glyphs is None:
            raise TTLibError("Font contains no outlines")

        return glyphs
Пример #8
0
    def __setitem__(self, tag, data):
        """Write raw table data to disk."""
        if tag in self.tables:
            raise TTLibError("cannot rewrite '%s' table" % tag)

        entry = self.DirectoryEntry()
        entry.tag = tag
        entry.offset = self.nextTableOffset
        if tag == 'head':
            entry.checkSum = calcChecksum(data[:8] + b'\0\0\0\0' + data[12:])
            self.headTable = data
            entry.uncompressed = True
        else:
            entry.checkSum = calcChecksum(data)
        entry.saveData(self.file, data)

        if self.flavor == "woff":
            entry.origOffset = self.origNextTableOffset
            self.origNextTableOffset += (entry.origLength + 3) & ~3

        self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3)
        # Add NUL bytes to pad the table data to a 4-byte boundary.
        # Don't depend on f.seek() as we need to add the padding even if no
        # subsequent write follows (seek is lazy), ie. after the final table
        # in the font.
        self.file.write(b'\0' * (self.nextTableOffset - self.file.tell()))
        assert self.nextTableOffset == self.file.tell()

        self.setEntry(tag, entry)
Пример #9
0
 def fromXML(self, name, attrs, content, ttFont):
     if name == "hexdata":
         self.data[attrs["tag"]] = readHex(content)
     elif name == "text" and attrs["tag"] in ["dlng", "slng"]:
         self.data[attrs["tag"]] = strjoin(content).strip()
     else:
         raise TTLibError("can't handle '%s' element" % name)
Пример #10
0
	def decompilePoints_(numPointsInGlyph, data, offset):
		"""(numPointsInGlyph, data, offset) --> ([point1, point2, ...], newOffset)"""
		pos = offset
		numPointsInData = byteord(data[pos])
		pos += 1
		if (numPointsInData & POINTS_ARE_WORDS) != 0:
			numPointsInData = (numPointsInData & POINT_RUN_COUNT_MASK) << 8 | byteord(data[pos])
			pos += 1
		if numPointsInData == 0:
			return (range(numPointsInGlyph), pos)
		result = []
		while len(result) < numPointsInData:
			runHeader = byteord(data[pos])
			pos += 1
			numPointsInRun = (runHeader & POINT_RUN_COUNT_MASK) + 1
			point = 0
			if (runHeader & POINTS_ARE_WORDS) == 0:
				for _ in range(numPointsInRun):
					point += byteord(data[pos])
					pos += 1
					result.append(point)
			else:
				for _ in range(numPointsInRun):
					point += struct.unpack(">H", data[pos:pos+2])[0]
					pos += 2
					result.append(point)
		if max(result) >= numPointsInGlyph:
			raise TTLibError("malformed 'gvar' table")
		return (result, pos)
Пример #11
0
	def _decodeBBox(self, glyphID, glyph):
		haveBBox = bool(self.bboxBitmap[glyphID >> 3] & (0x80 >> (glyphID & 7)))
		if glyph.isComposite() and not haveBBox:
			raise TTLibError('no bbox values for composite glyph %d' % glyphID)
		if haveBBox:
			dummy, self.bboxStream = sstruct.unpack2(bboxFormat, self.bboxStream, glyph)
		else:
			glyph.recalcBounds(self)
Пример #12
0
def unpackBase128(data):
    r""" Read one to five bytes from UIntBase128-encoded input string, and return
	a tuple containing the decoded integer plus any leftover data.

	>>> unpackBase128(b'\x3f\x00\x00') == (63, b"\x00\x00")
	True
	>>> unpackBase128(b'\x8f\xff\xff\xff\x7f')[0] == 4294967295
	True
	>>> unpackBase128(b'\x80\x80\x3f')  # doctest: +IGNORE_EXCEPTION_DETAIL
	Traceback (most recent call last):
	  File "<stdin>", line 1, in ?
	TTLibError: UIntBase128 value must not start with leading zeros
	>>> unpackBase128(b'\x8f\xff\xff\xff\xff\x7f')[0]  # doctest: +IGNORE_EXCEPTION_DETAIL
	Traceback (most recent call last):
	  File "<stdin>", line 1, in ?
	TTLibError: UIntBase128-encoded sequence is longer than 5 bytes
	>>> unpackBase128(b'\x90\x80\x80\x80\x00')[0]  # doctest: +IGNORE_EXCEPTION_DETAIL
	Traceback (most recent call last):
	  File "<stdin>", line 1, in ?
	TTLibError: UIntBase128 value exceeds 2**32-1
	"""
    if len(data) == 0:
        raise TTLibError('not enough data to unpack UIntBase128')
    result = 0
    if byteord(data[0]) == 0x80:
        # font must be rejected if UIntBase128 value starts with 0x80
        raise TTLibError('UIntBase128 value must not start with leading zeros')
    for i in range(woff2Base128MaxSize):
        if len(data) == 0:
            raise TTLibError('not enough data to unpack UIntBase128')
        code = byteord(data[0])
        data = data[1:]
        # if any of the top seven bits are set then we're about to overflow
        if result & 0xFE000000:
            raise TTLibError('UIntBase128 value exceeds 2**32-1')
        # set current value = old value times 128 bitwise-or (byte bitwise-and 127)
        result = (result << 7) | (code & 0x7f)
        # repeat until the most significant bit of byte is false
        if (code & 0x80) == 0:
            # return result plus left over data
            return result, data
    # make sure not to exceed the size bound
    raise TTLibError('UIntBase128-encoded sequence is longer than 5 bytes')
Пример #13
0
def unpack255UShort(data):
    """ Read one to three bytes from 255UInt16-encoded input string, and return a
	tuple containing the decoded integer plus any leftover data.

	>>> unpack255UShort(bytechr(252))[0]
	252

	Note that some numbers (e.g. 506) can have multiple encodings:
	>>> unpack255UShort(struct.pack("BB", 254, 0))[0]
	506
	>>> unpack255UShort(struct.pack("BB", 255, 253))[0]
	506
	>>> unpack255UShort(struct.pack("BBB", 253, 1, 250))[0]
	506
	"""
    code = byteord(data[:1])
    data = data[1:]
    if code == 253:
        # read two more bytes as an unsigned short
        if len(data) < 2:
            raise TTLibError('not enough data to unpack 255UInt16')
        result, = struct.unpack(">H", data[:2])
        data = data[2:]
    elif code == 254:
        # read another byte, plus 253 * 2
        if len(data) == 0:
            raise TTLibError('not enough data to unpack 255UInt16')
        result = byteord(data[:1])
        result += 506
        data = data[1:]
    elif code == 255:
        # read another byte, plus 253
        if len(data) == 0:
            raise TTLibError('not enough data to unpack 255UInt16')
        result = byteord(data[:1])
        result += 253
        data = data[1:]
    else:
        # leave as is if lower than 253
        result = code
    # return result plus left over data
    return result, data
Пример #14
0
    def decompile(self, data, offset):
        # initial offset is from the start of trak table to the current TrackData
        trackDataHeader = data[offset:offset + TRACK_DATA_FORMAT_SIZE]
        if len(trackDataHeader) != TRACK_DATA_FORMAT_SIZE:
            raise TTLibError('not enough data to decompile TrackData header')
        sstruct.unpack(TRACK_DATA_FORMAT, trackDataHeader, self)
        offset += TRACK_DATA_FORMAT_SIZE

        nSizes = self.nSizes
        sizeTableOffset = self.sizeTableOffset
        sizeTable = []
        for i in range(nSizes):
            sizeValueData = data[sizeTableOffset:sizeTableOffset +
                                 SIZE_VALUE_FORMAT_SIZE]
            if len(sizeValueData) < SIZE_VALUE_FORMAT_SIZE:
                raise TTLibError(
                    'not enough data to decompile TrackData size subtable')
            sizeValue, = struct.unpack(SIZE_VALUE_FORMAT, sizeValueData)
            sizeTable.append(fi2fl(sizeValue, 16))
            sizeTableOffset += SIZE_VALUE_FORMAT_SIZE

        for i in range(self.nTracks):
            entry = TrackTableEntry()
            entryData = data[offset:offset + TRACK_TABLE_ENTRY_FORMAT_SIZE]
            if len(entryData) < TRACK_TABLE_ENTRY_FORMAT_SIZE:
                raise TTLibError(
                    'not enough data to decompile TrackTableEntry record')
            sstruct.unpack(TRACK_TABLE_ENTRY_FORMAT, entryData, entry)
            perSizeOffset = entry.offset
            for j in range(nSizes):
                size = sizeTable[j]
                perSizeValueData = data[perSizeOffset:perSizeOffset +
                                        PER_SIZE_VALUE_FORMAT_SIZE]
                if len(perSizeValueData) < PER_SIZE_VALUE_FORMAT_SIZE:
                    raise TTLibError(
                        'not enough data to decompile per-size track values')
                perSizeValue, = struct.unpack(PER_SIZE_VALUE_FORMAT,
                                              perSizeValueData)
                entry[size] = perSizeValue
                perSizeOffset += PER_SIZE_VALUE_FORMAT_SIZE
            self[entry.track] = entry
            offset += TRACK_TABLE_ENTRY_FORMAT_SIZE
def _(fonts, **kwargs):
    skip = 0
    for font in fonts:
        try:
            otf_to_ttf(font, **kwargs)
        except TTLibError as warn:
            skip += 1
            log.warning(warn)

    if skip == len(fonts):
        raise TTLibError("a Font Collection that has Not a OpenType font")
Пример #16
0
 def sizes(self):
     if not self:
         return frozenset()
     tracks = list(self.tracks())
     sizes = self[tracks.pop(0)].sizes()
     for track in tracks:
         entrySizes = self[track].sizes()
         if sizes != entrySizes:
             raise TTLibError(
                 "'trak' table entries must specify the same sizes: "
                 "%s != %s" % (sorted(sizes), sorted(entrySizes)))
     return frozenset(sizes)
Пример #17
0
 def _reconstructLoca(self):
     """ Return reconstructed loca table data. """
     if 'loca' not in self.ttFont:
         # make sure glyf is reconstructed first
         self.tables['glyf'].data = self.reconstructTable('glyf')
     locaTable = self.ttFont['loca']
     data = locaTable.compile(self.ttFont)
     if len(data) != self.tables['loca'].origLength:
         raise TTLibError(
             "reconstructed 'loca' table doesn't match original size: "
             "expected %d, found %d" %
             (self.tables['loca'].origLength, len(data)))
     return data
Пример #18
0
	def fromString(self, data):
		if len(data) < 1:
			raise TTLibError("can't read table 'flags': not enough data")
		dummy, data = sstruct.unpack2(woff2FlagsFormat, data, self)
		if self.flags & 0x3F == 0x3F:
			# if bits [0..5] of the flags byte == 63, read a 4-byte arbitrary tag value
			if len(data) < woff2UnknownTagSize:
				raise TTLibError("can't read table 'tag': not enough data")
			dummy, data = sstruct.unpack2(woff2UnknownTagFormat, data, self)
		else:
			# otherwise, tag is derived from a fixed 'Known Tags' table
			self.tag = woff2KnownTags[self.flags & 0x3F]
		self.tag = Tag(self.tag)
		self.origLength, data = unpackBase128(data)
		self.length = self.origLength
		if self.transformed:
			self.length, data = unpackBase128(data)
			if self.tag == 'loca' and self.length != 0:
				raise TTLibError(
					"the transformLength of the 'loca' table must be 0")
		# return left over data
		return data
Пример #19
0
def test_main_ttlib_error(tmpdir, monkeypatch, caplog):
    with pytest.raises(SystemExit):
        inpath = os.path.join("Tests", "ttx", "data", "TestTTF.ttx")
        outpath = tmpdir.join("TestTTF.ttf")
        args = ["-o", str(outpath), inpath]
        monkeypatch.setattr(
            ttx,
            "process",
            (lambda x, y: raise_exception(TTLibError("Test error"))),
        )
        ttx.main(args)

    assert "Test error" in caplog.text
Пример #20
0
 def transformTable(self, tag):
     """Return transformed table data."""
     if tag not in woff2TransformedTableTags:
         raise TTLibError("Transform for table '%s' is unknown" % tag)
     if tag == "loca":
         data = b""
     elif tag == "glyf":
         for tag in ('maxp', 'head', 'loca', 'glyf'):
             self._decompileTable(tag)
         glyfTable = self.ttFont['glyf']
         data = glyfTable.transform(self.ttFont)
     else:
         raise NotImplementedError
     return data
Пример #21
0
 def decompile(self, data, ttFont):
     headerSize = sstruct.calcsize(META_HEADER_FORMAT)
     header = sstruct.unpack(META_HEADER_FORMAT, data[0:headerSize])
     if header["version"] != 1:
         raise TTLibError("unsupported 'meta' version %d" %
                          header["version"])
     dataMapSize = sstruct.calcsize(DATA_MAP_FORMAT)
     for i in range(header["numDataMaps"]):
         dataMapOffset = headerSize + i * dataMapSize
         dataMap = sstruct.unpack(
             DATA_MAP_FORMAT,
             data[dataMapOffset:dataMapOffset + dataMapSize])
         tag = dataMap["tag"]
         offset = dataMap["dataOffset"]
         self.data[tag] = data[offset:offset + dataMap["dataLength"]]
Пример #22
0
 def reconstructTable(self, tag):
     """Reconstruct table named 'tag' from transformed data."""
     if tag not in woff2TransformedTableTags:
         raise TTLibError("transform for table '%s' is unknown" % tag)
     entry = self.tables[Tag(tag)]
     rawData = entry.loadData(self.transformBuffer)
     if tag == 'glyf':
         # no need to pad glyph data when reconstructing
         padding = self.padding if hasattr(self, 'padding') else None
         data = self._reconstructGlyf(rawData, padding)
     elif tag == 'loca':
         data = self._reconstructLoca()
     else:
         raise NotImplementedError
     return data
Пример #23
0
 def _decompileTable(self, tag):
     """ Fetch table data, decompile it, and store it inside self.ttFont. """
     tag = Tag(tag)
     if tag not in self.tables:
         raise TTLibError("missing required table: %s" % tag)
     if self.ttFont.isLoaded(tag):
         return
     data = self.tables[tag].data
     if tag == 'loca':
         tableClass = WOFF2LocaTable
     elif tag == 'glyf':
         tableClass = WOFF2GlyfTable
     else:
         tableClass = getTableClass(tag)
     table = tableClass(tag)
     self.ttFont.tables[tag] = table
     table.decompile(data, self.ttFont)
Пример #24
0
    def __setitem__(self, tag, data):
        """Associate new entry named 'tag' with raw table data."""
        if tag in self.tables:
            raise TTLibError("cannot rewrite '%s' table" % tag)
        if tag == 'DSIG':
            # always drop DSIG table, since the encoding process can invalidate it
            self.numTables -= 1
            return

        entry = self.DirectoryEntry()
        entry.tag = Tag(tag)
        entry.flags = getKnownTagIndex(entry.tag)
        # WOFF2 table data are written to disk only on close(), after all tags
        # have been specified
        entry.data = data

        self.tables[tag] = entry
Пример #25
0
    def save(self, file, reorderTables=True):
        """Save the font to disk.

		Args:
			file: Similarly to the constructor, can be either a pathname or a writable
				file object.
			reorderTables (Option[bool]): If true (the default), reorder the tables,
				sorting them by tag (recommended by the OpenType specification). If
				false, retain the original font order. If None, reorder by table
				dependency (fastest).
		"""
        if not hasattr(file, "write"):
            if self.lazy and self.reader.file.name == file:
                raise TTLibError(
                    "Can't overwrite TTFont when 'lazy' attribute is True")
            createStream = True
        else:
            # assume "file" is a writable file object
            createStream = False

        tmp = BytesIO()

        writer_reordersTables = self._save(tmp)

        if not (reorderTables is None or writer_reordersTables or
                (reorderTables is False and self.reader is None)):
            if reorderTables is False:
                # sort tables using the original font's order
                tableOrder = list(self.reader.keys())
            else:
                # use the recommended order from the OpenType specification
                tableOrder = None
            tmp.flush()
            tmp2 = BytesIO()
            reorderFontTables(tmp, tmp2, tableOrder)
            tmp.close()
            tmp = tmp2

        if createStream:
            # "file" is a path
            with open(file, "wb") as file:
                file.write(tmp.getvalue())
        else:
            file.write(tmp.getvalue())

        tmp.close()
Пример #26
0
 def decompile(self, data, ttFont):
     axisTags = [axis.axisTag for axis in ttFont["fvar"].axes]
     header = {}
     headerSize = sstruct.calcsize(AVAR_HEADER_FORMAT)
     header = sstruct.unpack(AVAR_HEADER_FORMAT, data[0:headerSize])
     majorVersion = header["majorVersion"]
     if majorVersion != 1:
         raise TTLibError("unsupported 'avar' version %d" % majorVersion)
     pos = headerSize
     for axis in axisTags:
         segments = self.segments[axis] = {}
         numPairs = struct.unpack(">H", data[pos:pos + 2])[0]
         pos = pos + 2
         for _ in range(numPairs):
             fromValue, toValue = struct.unpack(">hh", data[pos:pos + 4])
             segments[fi2fl(fromValue, 14)] = fi2fl(toValue, 14)
             pos = pos + 4
Пример #27
0
    def decompile(self, data, ttFont):
        if not self.apple:
            version, length, subtableFormat, coverage = struct.unpack(
                ">HHBB", data[:6])
            if version != 0:
                from fontTools.ttLib import TTLibError
                raise TTLibError("unsupported kern subtable version: %d" %
                                 version)
            tupleIndex = None
            # Should we also assert length == len(data)?
            data = data[6:]
        else:
            length, coverage, subtableFormat, tupleIndex = struct.unpack(
                ">LBBH", data[:8])
            data = data[8:]
        assert self.format == subtableFormat, "unsupported format"
        self.coverage = coverage
        self.tupleIndex = tupleIndex

        self.kernTable = kernTable = {}

        nPairs, searchRange, entrySelector, rangeShift = struct.unpack(
            ">HHHH", data[:8])
        data = data[8:]

        nPairs = min(nPairs, len(data) // 6)
        datas = array.array("H", data[:6 * nPairs])
        if sys.byteorder != "big":  # pragma: no cover
            datas.byteswap()
        it = iter(datas)
        glyphOrder = ttFont.getGlyphOrder()
        for k in range(nPairs):
            left, right, value = next(it), next(it), next(it)
            if value >= 32768:
                value -= 65536
            try:
                kernTable[(glyphOrder[left], glyphOrder[right])] = value
            except IndexError:
                # Slower, but will not throw an IndexError on an invalid
                # glyph id.
                kernTable[(ttFont.getGlyphName(left),
                           ttFont.getGlyphName(right))] = value
        if len(data) > 6 * nPairs + 4:  # Ignore up to 4 bytes excess
            log.warning("excess data in 'kern' subtable: %d bytes",
                        len(data) - 6 * nPairs)
Пример #28
0
 def decompile(self, data, ttFont):
     axisTags = [axis.axisTag for axis in ttFont["fvar"].axes]
     header = {}
     headerSize = sstruct.calcsize(AVAR_HEADER_FORMAT)
     header = sstruct.unpack(AVAR_HEADER_FORMAT, data[0:headerSize])
     if header["version"] != 0x00010000:
         raise TTLibError("unsupported 'avar' version %04x" %
                          header["version"])
     pos = headerSize
     for axis in axisTags:
         segments = self.segments[axis] = {}
         numPairs = struct.unpack(">H", data[pos:pos + 2])[0]
         pos = pos + 2
         for _ in range(numPairs):
             fromValue, toValue = struct.unpack(">hh", data[pos:pos + 4])
             segments[fixedToFloat(fromValue,
                                   14)] = fixedToFloat(toValue, 14)
             pos = pos + 4
     self.fixupSegments_()
def otf_to_ttf(ttFont, post_format=POST_FORMAT, **kwargs):
    if ttFont.sfntVersion != "OTTO":
        raise TTLibError("Not a OpenType font (bad sfntVersion)")
    assert "CFF " in ttFont

    glyphOrder = ttFont.getGlyphOrder()

    ttFont["loca"] = newTable("loca")
    ttFont["glyf"] = glyf = newTable("glyf")
    glyf.glyphOrder = glyphOrder
    glyf.glyphs = glyphs_to_quadratic(ttFont.getGlyphSet(), **kwargs)
    del ttFont["CFF "]
    if "VORG" in ttFont:
        del ttFont["VORG"]
    glyf.compile(ttFont)
    update_hmtx(ttFont, glyf)

    ttFont["maxp"] = maxp = newTable("maxp")
    maxp.tableVersion = 0x00010000
    maxp.maxZones = 1
    maxp.maxTwilightPoints = 0
    maxp.maxStorage = 0
    maxp.maxFunctionDefs = 0
    maxp.maxInstructionDefs = 0
    maxp.maxStackElements = 0
    maxp.maxSizeOfInstructions = 0
    maxp.maxComponentElements = max(
        len(g.components if hasattr(g, 'components') else [])
        for g in glyf.glyphs.values())
    maxp.compile(ttFont)

    post = ttFont["post"]
    post.formatType = post_format
    post.extraNames = []
    post.mapping = {}
    post.glyphOrder = glyphOrder
    try:
        post.compile(ttFont)
    except OverflowError:
        post.formatType = 3
        log.warning("Dropping glyph names, they do not fit in 'post' table.")

    ttFont.sfntVersion = "\000\001\000\000"
Пример #30
0
    def getGlyphSet(self, preferCFF=True, location=None, normalized=False):
        """Return a generic GlyphSet, which is a dict-like object
		mapping glyph names to glyph objects. The returned glyph objects
		have a .draw() method that supports the Pen protocol, and will
		have an attribute named 'width'.

		If the font is CFF-based, the outlines will be taken from the 'CFF ' or
		'CFF2' tables. Otherwise the outlines will be taken from the 'glyf' table.
		If the font contains both a 'CFF '/'CFF2' and a 'glyf' table, you can use
		the 'preferCFF' argument to specify which one should be taken. If the
		font contains both a 'CFF ' and a 'CFF2' table, the latter is taken.

		If the 'location' parameter is set, it should be a dictionary mapping
		four-letter variation tags to their float values, and the returned
		glyph-set will represent an instance of a variable font at that location.
		If the 'normalized' variable is set to True, that location is interpretted
		as in the normalized (-1..+1) space, otherwise it is in the font's defined
		axes space.
		"""
        glyphs = None
        if (preferCFF and any(tb in self for tb in ["CFF ", "CFF2"])
                or ("glyf" not in self and any(tb in self
                                               for tb in ["CFF ", "CFF2"]))):
            table_tag = "CFF2" if "CFF2" in self else "CFF "
            if location:
                raise NotImplementedError  # TODO
            glyphs = _TTGlyphSet(
                self,
                list(self[table_tag].cff.values())[0].CharStrings, _TTGlyphCFF)

        if glyphs is None and "glyf" in self:
            if location and 'gvar' in self:
                glyphs = _TTVarGlyphSet(self,
                                        location=location,
                                        normalized=normalized)
            else:
                glyphs = _TTGlyphSet(self, self["glyf"], _TTGlyphGlyf)

        if glyphs is None:
            raise TTLibError("Font contains no outlines")

        return glyphs