sfnt.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. """ttLib/sfnt.py -- low-level module to deal with the sfnt file format.
  2. Defines two public classes:
  3. SFNTReader
  4. SFNTWriter
  5. (Normally you don't have to use these classes explicitly; they are
  6. used automatically by ttLib.TTFont.)
  7. The reading and writing of sfnt files is separated in two distinct
  8. classes, since whenever the number of tables changes or whenever
  9. a table's length changes you need to rewrite the whole file anyway.
  10. """
  11. from io import BytesIO
  12. from types import SimpleNamespace
  13. from fontTools.misc.textTools import Tag
  14. from fontTools.misc import sstruct
  15. from fontTools.ttLib import TTLibError, TTLibFileIsCollectionError
  16. import struct
  17. from collections import OrderedDict
  18. import logging
  19. log = logging.getLogger(__name__)
  20. class SFNTReader(object):
  21. def __new__(cls, *args, **kwargs):
  22. """Return an instance of the SFNTReader sub-class which is compatible
  23. with the input file type.
  24. """
  25. if args and cls is SFNTReader:
  26. infile = args[0]
  27. infile.seek(0)
  28. sfntVersion = Tag(infile.read(4))
  29. infile.seek(0)
  30. if sfntVersion == "wOF2":
  31. # return new WOFF2Reader object
  32. from fontTools.ttLib.woff2 import WOFF2Reader
  33. return object.__new__(WOFF2Reader)
  34. # return default object
  35. return object.__new__(cls)
  36. def __init__(self, file, checkChecksums=0, fontNumber=-1):
  37. self.file = file
  38. self.checkChecksums = checkChecksums
  39. self.flavor = None
  40. self.flavorData = None
  41. self.DirectoryEntry = SFNTDirectoryEntry
  42. self.file.seek(0)
  43. self.sfntVersion = self.file.read(4)
  44. self.file.seek(0)
  45. if self.sfntVersion == b"ttcf":
  46. header = readTTCHeader(self.file)
  47. numFonts = header.numFonts
  48. if not 0 <= fontNumber < numFonts:
  49. raise TTLibFileIsCollectionError(
  50. "specify a font number between 0 and %d (inclusive)"
  51. % (numFonts - 1)
  52. )
  53. self.numFonts = numFonts
  54. self.file.seek(header.offsetTable[fontNumber])
  55. data = self.file.read(sfntDirectorySize)
  56. if len(data) != sfntDirectorySize:
  57. raise TTLibError("Not a Font Collection (not enough data)")
  58. sstruct.unpack(sfntDirectoryFormat, data, self)
  59. elif self.sfntVersion == b"wOFF":
  60. self.flavor = "woff"
  61. self.DirectoryEntry = WOFFDirectoryEntry
  62. data = self.file.read(woffDirectorySize)
  63. if len(data) != woffDirectorySize:
  64. raise TTLibError("Not a WOFF font (not enough data)")
  65. sstruct.unpack(woffDirectoryFormat, data, self)
  66. else:
  67. data = self.file.read(sfntDirectorySize)
  68. if len(data) != sfntDirectorySize:
  69. raise TTLibError("Not a TrueType or OpenType font (not enough data)")
  70. sstruct.unpack(sfntDirectoryFormat, data, self)
  71. self.sfntVersion = Tag(self.sfntVersion)
  72. if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"):
  73. raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")
  74. tables = {}
  75. for i in range(self.numTables):
  76. entry = self.DirectoryEntry()
  77. entry.fromFile(self.file)
  78. tag = Tag(entry.tag)
  79. tables[tag] = entry
  80. self.tables = OrderedDict(sorted(tables.items(), key=lambda i: i[1].offset))
  81. # Load flavor data if any
  82. if self.flavor == "woff":
  83. self.flavorData = WOFFFlavorData(self)
  84. def has_key(self, tag):
  85. return tag in self.tables
  86. __contains__ = has_key
  87. def keys(self):
  88. return self.tables.keys()
  89. def __getitem__(self, tag):
  90. """Fetch the raw table data."""
  91. entry = self.tables[Tag(tag)]
  92. data = entry.loadData(self.file)
  93. if self.checkChecksums:
  94. if tag == "head":
  95. # Beh: we have to special-case the 'head' table.
  96. checksum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
  97. else:
  98. checksum = calcChecksum(data)
  99. if self.checkChecksums > 1:
  100. # Be obnoxious, and barf when it's wrong
  101. assert checksum == entry.checkSum, "bad checksum for '%s' table" % tag
  102. elif checksum != entry.checkSum:
  103. # Be friendly, and just log a warning.
  104. log.warning("bad checksum for '%s' table", tag)
  105. return data
  106. def __delitem__(self, tag):
  107. del self.tables[Tag(tag)]
  108. def close(self):
  109. self.file.close()
  110. # We define custom __getstate__ and __setstate__ to make SFNTReader pickle-able
  111. # and deepcopy-able. When a TTFont is loaded as lazy=True, SFNTReader holds a
  112. # reference to an external file object which is not pickleable. So in __getstate__
  113. # we store the file name and current position, and in __setstate__ we reopen the
  114. # same named file after unpickling.
  115. def __getstate__(self):
  116. if isinstance(self.file, BytesIO):
  117. # BytesIO is already pickleable, return the state unmodified
  118. return self.__dict__
  119. # remove unpickleable file attribute, and only store its name and pos
  120. state = self.__dict__.copy()
  121. del state["file"]
  122. state["_filename"] = self.file.name
  123. state["_filepos"] = self.file.tell()
  124. return state
  125. def __setstate__(self, state):
  126. if "file" not in state:
  127. self.file = open(state.pop("_filename"), "rb")
  128. self.file.seek(state.pop("_filepos"))
  129. self.__dict__.update(state)
  130. # default compression level for WOFF 1.0 tables and metadata
  131. ZLIB_COMPRESSION_LEVEL = 6
  132. # if set to True, use zopfli instead of zlib for compressing WOFF 1.0.
  133. # The Python bindings are available at https://pypi.python.org/pypi/zopfli
  134. USE_ZOPFLI = False
  135. # mapping between zlib's compression levels and zopfli's 'numiterations'.
  136. # Use lower values for files over several MB in size or it will be too slow
  137. ZOPFLI_LEVELS = {
  138. # 0: 0, # can't do 0 iterations...
  139. 1: 1,
  140. 2: 3,
  141. 3: 5,
  142. 4: 8,
  143. 5: 10,
  144. 6: 15,
  145. 7: 25,
  146. 8: 50,
  147. 9: 100,
  148. }
  149. def compress(data, level=ZLIB_COMPRESSION_LEVEL):
  150. """Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True,
  151. zopfli is used instead of the zlib module.
  152. The compression 'level' must be between 0 and 9. 1 gives best speed,
  153. 9 gives best compression (0 gives no compression at all).
  154. The default value is a compromise between speed and compression (6).
  155. """
  156. if not (0 <= level <= 9):
  157. raise ValueError("Bad compression level: %s" % level)
  158. if not USE_ZOPFLI or level == 0:
  159. from zlib import compress
  160. return compress(data, level)
  161. else:
  162. from zopfli.zlib import compress
  163. return compress(data, numiterations=ZOPFLI_LEVELS[level])
  164. class SFNTWriter(object):
  165. def __new__(cls, *args, **kwargs):
  166. """Return an instance of the SFNTWriter sub-class which is compatible
  167. with the specified 'flavor'.
  168. """
  169. flavor = None
  170. if kwargs and "flavor" in kwargs:
  171. flavor = kwargs["flavor"]
  172. elif args and len(args) > 3:
  173. flavor = args[3]
  174. if cls is SFNTWriter:
  175. if flavor == "woff2":
  176. # return new WOFF2Writer object
  177. from fontTools.ttLib.woff2 import WOFF2Writer
  178. return object.__new__(WOFF2Writer)
  179. # return default object
  180. return object.__new__(cls)
  181. def __init__(
  182. self,
  183. file,
  184. numTables,
  185. sfntVersion="\000\001\000\000",
  186. flavor=None,
  187. flavorData=None,
  188. ):
  189. self.file = file
  190. self.numTables = numTables
  191. self.sfntVersion = Tag(sfntVersion)
  192. self.flavor = flavor
  193. self.flavorData = flavorData
  194. if self.flavor == "woff":
  195. self.directoryFormat = woffDirectoryFormat
  196. self.directorySize = woffDirectorySize
  197. self.DirectoryEntry = WOFFDirectoryEntry
  198. self.signature = "wOFF"
  199. # to calculate WOFF checksum adjustment, we also need the original SFNT offsets
  200. self.origNextTableOffset = (
  201. sfntDirectorySize + numTables * sfntDirectoryEntrySize
  202. )
  203. else:
  204. assert not self.flavor, "Unknown flavor '%s'" % self.flavor
  205. self.directoryFormat = sfntDirectoryFormat
  206. self.directorySize = sfntDirectorySize
  207. self.DirectoryEntry = SFNTDirectoryEntry
  208. from fontTools.ttLib import getSearchRange
  209. self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
  210. numTables, 16
  211. )
  212. self.directoryOffset = self.file.tell()
  213. self.nextTableOffset = (
  214. self.directoryOffset
  215. + self.directorySize
  216. + numTables * self.DirectoryEntry.formatSize
  217. )
  218. # clear out directory area
  219. self.file.seek(self.nextTableOffset)
  220. # make sure we're actually where we want to be. (old cStringIO bug)
  221. self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
  222. self.tables = OrderedDict()
  223. def setEntry(self, tag, entry):
  224. if tag in self.tables:
  225. raise TTLibError("cannot rewrite '%s' table" % tag)
  226. self.tables[tag] = entry
  227. def __setitem__(self, tag, data):
  228. """Write raw table data to disk."""
  229. if tag in self.tables:
  230. raise TTLibError("cannot rewrite '%s' table" % tag)
  231. entry = self.DirectoryEntry()
  232. entry.tag = tag
  233. entry.offset = self.nextTableOffset
  234. if tag == "head":
  235. entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])
  236. self.headTable = data
  237. entry.uncompressed = True
  238. else:
  239. entry.checkSum = calcChecksum(data)
  240. entry.saveData(self.file, data)
  241. if self.flavor == "woff":
  242. entry.origOffset = self.origNextTableOffset
  243. self.origNextTableOffset += (entry.origLength + 3) & ~3
  244. self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3)
  245. # Add NUL bytes to pad the table data to a 4-byte boundary.
  246. # Don't depend on f.seek() as we need to add the padding even if no
  247. # subsequent write follows (seek is lazy), ie. after the final table
  248. # in the font.
  249. self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))
  250. assert self.nextTableOffset == self.file.tell()
  251. self.setEntry(tag, entry)
  252. def __getitem__(self, tag):
  253. return self.tables[tag]
  254. def close(self):
  255. """All tables must have been written to disk. Now write the
  256. directory.
  257. """
  258. tables = sorted(self.tables.items())
  259. if len(tables) != self.numTables:
  260. raise TTLibError(
  261. "wrong number of tables; expected %d, found %d"
  262. % (self.numTables, len(tables))
  263. )
  264. if self.flavor == "woff":
  265. self.signature = b"wOFF"
  266. self.reserved = 0
  267. self.totalSfntSize = 12
  268. self.totalSfntSize += 16 * len(tables)
  269. for tag, entry in tables:
  270. self.totalSfntSize += (entry.origLength + 3) & ~3
  271. data = self.flavorData if self.flavorData else WOFFFlavorData()
  272. if data.majorVersion is not None and data.minorVersion is not None:
  273. self.majorVersion = data.majorVersion
  274. self.minorVersion = data.minorVersion
  275. else:
  276. if hasattr(self, "headTable"):
  277. self.majorVersion, self.minorVersion = struct.unpack(
  278. ">HH", self.headTable[4:8]
  279. )
  280. else:
  281. self.majorVersion = self.minorVersion = 0
  282. if data.metaData:
  283. self.metaOrigLength = len(data.metaData)
  284. self.file.seek(0, 2)
  285. self.metaOffset = self.file.tell()
  286. compressedMetaData = compress(data.metaData)
  287. self.metaLength = len(compressedMetaData)
  288. self.file.write(compressedMetaData)
  289. else:
  290. self.metaOffset = self.metaLength = self.metaOrigLength = 0
  291. if data.privData:
  292. self.file.seek(0, 2)
  293. off = self.file.tell()
  294. paddedOff = (off + 3) & ~3
  295. self.file.write(b"\0" * (paddedOff - off))
  296. self.privOffset = self.file.tell()
  297. self.privLength = len(data.privData)
  298. self.file.write(data.privData)
  299. else:
  300. self.privOffset = self.privLength = 0
  301. self.file.seek(0, 2)
  302. self.length = self.file.tell()
  303. else:
  304. assert not self.flavor, "Unknown flavor '%s'" % self.flavor
  305. pass
  306. directory = sstruct.pack(self.directoryFormat, self)
  307. self.file.seek(self.directoryOffset + self.directorySize)
  308. seenHead = 0
  309. for tag, entry in tables:
  310. if tag == "head":
  311. seenHead = 1
  312. directory = directory + entry.toString()
  313. if seenHead:
  314. self.writeMasterChecksum(directory)
  315. self.file.seek(self.directoryOffset)
  316. self.file.write(directory)
  317. def _calcMasterChecksum(self, directory):
  318. # calculate checkSumAdjustment
  319. tags = list(self.tables.keys())
  320. checksums = []
  321. for i in range(len(tags)):
  322. checksums.append(self.tables[tags[i]].checkSum)
  323. if self.DirectoryEntry != SFNTDirectoryEntry:
  324. # Create a SFNT directory for checksum calculation purposes
  325. from fontTools.ttLib import getSearchRange
  326. self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(
  327. self.numTables, 16
  328. )
  329. directory = sstruct.pack(sfntDirectoryFormat, self)
  330. tables = sorted(self.tables.items())
  331. for tag, entry in tables:
  332. sfntEntry = SFNTDirectoryEntry()
  333. sfntEntry.tag = entry.tag
  334. sfntEntry.checkSum = entry.checkSum
  335. sfntEntry.offset = entry.origOffset
  336. sfntEntry.length = entry.origLength
  337. directory = directory + sfntEntry.toString()
  338. directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize
  339. assert directory_end == len(directory)
  340. checksums.append(calcChecksum(directory))
  341. checksum = sum(checksums) & 0xFFFFFFFF
  342. # BiboAfba!
  343. checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF
  344. return checksumadjustment
  345. def writeMasterChecksum(self, directory):
  346. checksumadjustment = self._calcMasterChecksum(directory)
  347. # write the checksum to the file
  348. self.file.seek(self.tables["head"].offset + 8)
  349. self.file.write(struct.pack(">L", checksumadjustment))
  350. def reordersTables(self):
  351. return False
  352. # -- sfnt directory helpers and cruft
  353. ttcHeaderFormat = """
  354. > # big endian
  355. TTCTag: 4s # "ttcf"
  356. Version: L # 0x00010000 or 0x00020000
  357. numFonts: L # number of fonts
  358. # OffsetTable[numFonts]: L # array with offsets from beginning of file
  359. # ulDsigTag: L # version 2.0 only
  360. # ulDsigLength: L # version 2.0 only
  361. # ulDsigOffset: L # version 2.0 only
  362. """
  363. ttcHeaderSize = sstruct.calcsize(ttcHeaderFormat)
  364. sfntDirectoryFormat = """
  365. > # big endian
  366. sfntVersion: 4s
  367. numTables: H # number of tables
  368. searchRange: H # (max2 <= numTables)*16
  369. entrySelector: H # log2(max2 <= numTables)
  370. rangeShift: H # numTables*16-searchRange
  371. """
  372. sfntDirectorySize = sstruct.calcsize(sfntDirectoryFormat)
  373. sfntDirectoryEntryFormat = """
  374. > # big endian
  375. tag: 4s
  376. checkSum: L
  377. offset: L
  378. length: L
  379. """
  380. sfntDirectoryEntrySize = sstruct.calcsize(sfntDirectoryEntryFormat)
  381. woffDirectoryFormat = """
  382. > # big endian
  383. signature: 4s # "wOFF"
  384. sfntVersion: 4s
  385. length: L # total woff file size
  386. numTables: H # number of tables
  387. reserved: H # set to 0
  388. totalSfntSize: L # uncompressed size
  389. majorVersion: H # major version of WOFF file
  390. minorVersion: H # minor version of WOFF file
  391. metaOffset: L # offset to metadata block
  392. metaLength: L # length of compressed metadata
  393. metaOrigLength: L # length of uncompressed metadata
  394. privOffset: L # offset to private data block
  395. privLength: L # length of private data block
  396. """
  397. woffDirectorySize = sstruct.calcsize(woffDirectoryFormat)
  398. woffDirectoryEntryFormat = """
  399. > # big endian
  400. tag: 4s
  401. offset: L
  402. length: L # compressed length
  403. origLength: L # original length
  404. checkSum: L # original checksum
  405. """
  406. woffDirectoryEntrySize = sstruct.calcsize(woffDirectoryEntryFormat)
  407. class DirectoryEntry(object):
  408. def __init__(self):
  409. self.uncompressed = False # if True, always embed entry raw
  410. def fromFile(self, file):
  411. sstruct.unpack(self.format, file.read(self.formatSize), self)
  412. def fromString(self, str):
  413. sstruct.unpack(self.format, str, self)
  414. def toString(self):
  415. return sstruct.pack(self.format, self)
  416. def __repr__(self):
  417. if hasattr(self, "tag"):
  418. return "<%s '%s' at %x>" % (self.__class__.__name__, self.tag, id(self))
  419. else:
  420. return "<%s at %x>" % (self.__class__.__name__, id(self))
  421. def loadData(self, file):
  422. file.seek(self.offset)
  423. data = file.read(self.length)
  424. assert len(data) == self.length
  425. if hasattr(self.__class__, "decodeData"):
  426. data = self.decodeData(data)
  427. return data
  428. def saveData(self, file, data):
  429. if hasattr(self.__class__, "encodeData"):
  430. data = self.encodeData(data)
  431. self.length = len(data)
  432. file.seek(self.offset)
  433. file.write(data)
  434. def decodeData(self, rawData):
  435. return rawData
  436. def encodeData(self, data):
  437. return data
  438. class SFNTDirectoryEntry(DirectoryEntry):
  439. format = sfntDirectoryEntryFormat
  440. formatSize = sfntDirectoryEntrySize
  441. class WOFFDirectoryEntry(DirectoryEntry):
  442. format = woffDirectoryEntryFormat
  443. formatSize = woffDirectoryEntrySize
  444. def __init__(self):
  445. super(WOFFDirectoryEntry, self).__init__()
  446. # With fonttools<=3.1.2, the only way to set a different zlib
  447. # compression level for WOFF directory entries was to set the class
  448. # attribute 'zlibCompressionLevel'. This is now replaced by a globally
  449. # defined `ZLIB_COMPRESSION_LEVEL`, which is also applied when
  450. # compressing the metadata. For backward compatibility, we still
  451. # use the class attribute if it was already set.
  452. if not hasattr(WOFFDirectoryEntry, "zlibCompressionLevel"):
  453. self.zlibCompressionLevel = ZLIB_COMPRESSION_LEVEL
  454. def decodeData(self, rawData):
  455. import zlib
  456. if self.length == self.origLength:
  457. data = rawData
  458. else:
  459. assert self.length < self.origLength
  460. data = zlib.decompress(rawData)
  461. assert len(data) == self.origLength
  462. return data
  463. def encodeData(self, data):
  464. self.origLength = len(data)
  465. if not self.uncompressed:
  466. compressedData = compress(data, self.zlibCompressionLevel)
  467. if self.uncompressed or len(compressedData) >= self.origLength:
  468. # Encode uncompressed
  469. rawData = data
  470. self.length = self.origLength
  471. else:
  472. rawData = compressedData
  473. self.length = len(rawData)
  474. return rawData
  475. class WOFFFlavorData:
  476. Flavor = "woff"
  477. def __init__(self, reader=None):
  478. self.majorVersion = None
  479. self.minorVersion = None
  480. self.metaData = None
  481. self.privData = None
  482. if reader:
  483. self.majorVersion = reader.majorVersion
  484. self.minorVersion = reader.minorVersion
  485. if reader.metaLength:
  486. reader.file.seek(reader.metaOffset)
  487. rawData = reader.file.read(reader.metaLength)
  488. assert len(rawData) == reader.metaLength
  489. data = self._decompress(rawData)
  490. assert len(data) == reader.metaOrigLength
  491. self.metaData = data
  492. if reader.privLength:
  493. reader.file.seek(reader.privOffset)
  494. data = reader.file.read(reader.privLength)
  495. assert len(data) == reader.privLength
  496. self.privData = data
  497. def _decompress(self, rawData):
  498. import zlib
  499. return zlib.decompress(rawData)
  500. def calcChecksum(data):
  501. """Calculate the checksum for an arbitrary block of data.
  502. If the data length is not a multiple of four, it assumes
  503. it is to be padded with null byte.
  504. >>> print(calcChecksum(b"abcd"))
  505. 1633837924
  506. >>> print(calcChecksum(b"abcdxyz"))
  507. 3655064932
  508. """
  509. remainder = len(data) % 4
  510. if remainder:
  511. data += b"\0" * (4 - remainder)
  512. value = 0
  513. blockSize = 4096
  514. assert blockSize % 4 == 0
  515. for i in range(0, len(data), blockSize):
  516. block = data[i : i + blockSize]
  517. longs = struct.unpack(">%dL" % (len(block) // 4), block)
  518. value = (value + sum(longs)) & 0xFFFFFFFF
  519. return value
  520. def readTTCHeader(file):
  521. file.seek(0)
  522. data = file.read(ttcHeaderSize)
  523. if len(data) != ttcHeaderSize:
  524. raise TTLibError("Not a Font Collection (not enough data)")
  525. self = SimpleNamespace()
  526. sstruct.unpack(ttcHeaderFormat, data, self)
  527. if self.TTCTag != "ttcf":
  528. raise TTLibError("Not a Font Collection")
  529. assert self.Version == 0x00010000 or self.Version == 0x00020000, (
  530. "unrecognized TTC version 0x%08x" % self.Version
  531. )
  532. self.offsetTable = struct.unpack(
  533. ">%dL" % self.numFonts, file.read(self.numFonts * 4)
  534. )
  535. if self.Version == 0x00020000:
  536. pass # ignoring version 2.0 signatures
  537. return self
  538. def writeTTCHeader(file, numFonts):
  539. self = SimpleNamespace()
  540. self.TTCTag = "ttcf"
  541. self.Version = 0x00010000
  542. self.numFonts = numFonts
  543. file.seek(0)
  544. file.write(sstruct.pack(ttcHeaderFormat, self))
  545. offset = file.tell()
  546. file.write(struct.pack(">%dL" % self.numFonts, *([0] * self.numFonts)))
  547. return offset
  548. if __name__ == "__main__":
  549. import sys
  550. import doctest
  551. sys.exit(doctest.testmod().failed)