varStore.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. from fontTools.misc.roundTools import noRound, otRound
  2. from fontTools.misc.intTools import bit_count
  3. from fontTools.ttLib.tables import otTables as ot
  4. from fontTools.varLib.models import supportScalar
  5. from fontTools.varLib.builder import (
  6. buildVarRegionList,
  7. buildVarStore,
  8. buildVarRegion,
  9. buildVarData,
  10. )
  11. from functools import partial
  12. from collections import defaultdict
  13. from heapq import heappush, heappop
  14. NO_VARIATION_INDEX = ot.NO_VARIATION_INDEX
  15. ot.VarStore.NO_VARIATION_INDEX = NO_VARIATION_INDEX
  16. def _getLocationKey(loc):
  17. return tuple(sorted(loc.items(), key=lambda kv: kv[0]))
  18. class OnlineVarStoreBuilder(object):
  19. def __init__(self, axisTags):
  20. self._axisTags = axisTags
  21. self._regionMap = {}
  22. self._regionList = buildVarRegionList([], axisTags)
  23. self._store = buildVarStore(self._regionList, [])
  24. self._data = None
  25. self._model = None
  26. self._supports = None
  27. self._varDataIndices = {}
  28. self._varDataCaches = {}
  29. self._cache = {}
  30. def setModel(self, model):
  31. self.setSupports(model.supports)
  32. self._model = model
  33. def setSupports(self, supports):
  34. self._model = None
  35. self._supports = list(supports)
  36. if not self._supports[0]:
  37. del self._supports[0] # Drop base master support
  38. self._cache = {}
  39. self._data = None
  40. def finish(self, optimize=True):
  41. self._regionList.RegionCount = len(self._regionList.Region)
  42. self._store.VarDataCount = len(self._store.VarData)
  43. for data in self._store.VarData:
  44. data.ItemCount = len(data.Item)
  45. data.calculateNumShorts(optimize=optimize)
  46. return self._store
  47. def _add_VarData(self):
  48. regionMap = self._regionMap
  49. regionList = self._regionList
  50. regions = self._supports
  51. regionIndices = []
  52. for region in regions:
  53. key = _getLocationKey(region)
  54. idx = regionMap.get(key)
  55. if idx is None:
  56. varRegion = buildVarRegion(region, self._axisTags)
  57. idx = regionMap[key] = len(regionList.Region)
  58. regionList.Region.append(varRegion)
  59. regionIndices.append(idx)
  60. # Check if we have one already...
  61. key = tuple(regionIndices)
  62. varDataIdx = self._varDataIndices.get(key)
  63. if varDataIdx is not None:
  64. self._outer = varDataIdx
  65. self._data = self._store.VarData[varDataIdx]
  66. self._cache = self._varDataCaches[key]
  67. if len(self._data.Item) == 0xFFFF:
  68. # This is full. Need new one.
  69. varDataIdx = None
  70. if varDataIdx is None:
  71. self._data = buildVarData(regionIndices, [], optimize=False)
  72. self._outer = len(self._store.VarData)
  73. self._store.VarData.append(self._data)
  74. self._varDataIndices[key] = self._outer
  75. if key not in self._varDataCaches:
  76. self._varDataCaches[key] = {}
  77. self._cache = self._varDataCaches[key]
  78. def storeMasters(self, master_values, *, round=round):
  79. deltas = self._model.getDeltas(master_values, round=round)
  80. base = deltas.pop(0)
  81. return base, self.storeDeltas(deltas, round=noRound)
  82. def storeDeltas(self, deltas, *, round=round):
  83. deltas = [round(d) for d in deltas]
  84. if len(deltas) == len(self._supports) + 1:
  85. deltas = tuple(deltas[1:])
  86. else:
  87. assert len(deltas) == len(self._supports)
  88. deltas = tuple(deltas)
  89. varIdx = self._cache.get(deltas)
  90. if varIdx is not None:
  91. return varIdx
  92. if not self._data:
  93. self._add_VarData()
  94. inner = len(self._data.Item)
  95. if inner == 0xFFFF:
  96. # Full array. Start new one.
  97. self._add_VarData()
  98. return self.storeDeltas(deltas)
  99. self._data.addItem(deltas, round=noRound)
  100. varIdx = (self._outer << 16) + inner
  101. self._cache[deltas] = varIdx
  102. return varIdx
  103. def VarData_addItem(self, deltas, *, round=round):
  104. deltas = [round(d) for d in deltas]
  105. countUs = self.VarRegionCount
  106. countThem = len(deltas)
  107. if countUs + 1 == countThem:
  108. deltas = list(deltas[1:])
  109. else:
  110. assert countUs == countThem, (countUs, countThem)
  111. deltas = list(deltas)
  112. self.Item.append(deltas)
  113. self.ItemCount = len(self.Item)
  114. ot.VarData.addItem = VarData_addItem
  115. def VarRegion_get_support(self, fvar_axes):
  116. return {
  117. fvar_axes[i].axisTag: (reg.StartCoord, reg.PeakCoord, reg.EndCoord)
  118. for i, reg in enumerate(self.VarRegionAxis)
  119. if reg.PeakCoord != 0
  120. }
  121. ot.VarRegion.get_support = VarRegion_get_support
  122. def VarStore___bool__(self):
  123. return bool(self.VarData)
  124. ot.VarStore.__bool__ = VarStore___bool__
  125. class VarStoreInstancer(object):
  126. def __init__(self, varstore, fvar_axes, location={}):
  127. self.fvar_axes = fvar_axes
  128. assert varstore is None or varstore.Format == 1
  129. self._varData = varstore.VarData if varstore else []
  130. self._regions = varstore.VarRegionList.Region if varstore else []
  131. self.setLocation(location)
  132. def setLocation(self, location):
  133. self.location = dict(location)
  134. self._clearCaches()
  135. def _clearCaches(self):
  136. self._scalars = {}
  137. def _getScalar(self, regionIdx):
  138. scalar = self._scalars.get(regionIdx)
  139. if scalar is None:
  140. support = self._regions[regionIdx].get_support(self.fvar_axes)
  141. scalar = supportScalar(self.location, support)
  142. self._scalars[regionIdx] = scalar
  143. return scalar
  144. @staticmethod
  145. def interpolateFromDeltasAndScalars(deltas, scalars):
  146. delta = 0.0
  147. for d, s in zip(deltas, scalars):
  148. if not s:
  149. continue
  150. delta += d * s
  151. return delta
  152. def __getitem__(self, varidx):
  153. major, minor = varidx >> 16, varidx & 0xFFFF
  154. if varidx == NO_VARIATION_INDEX:
  155. return 0.0
  156. varData = self._varData
  157. scalars = [self._getScalar(ri) for ri in varData[major].VarRegionIndex]
  158. deltas = varData[major].Item[minor]
  159. return self.interpolateFromDeltasAndScalars(deltas, scalars)
  160. def interpolateFromDeltas(self, varDataIndex, deltas):
  161. varData = self._varData
  162. scalars = [self._getScalar(ri) for ri in varData[varDataIndex].VarRegionIndex]
  163. return self.interpolateFromDeltasAndScalars(deltas, scalars)
  164. #
  165. # Optimizations
  166. #
  167. # retainFirstMap - If true, major 0 mappings are retained. Deltas for unused indices are zeroed
  168. # advIdxes - Set of major 0 indices for advance deltas to be listed first. Other major 0 indices follow.
  169. def VarStore_subset_varidxes(
  170. self, varIdxes, optimize=True, retainFirstMap=False, advIdxes=set()
  171. ):
  172. # Sort out used varIdxes by major/minor.
  173. used = {}
  174. for varIdx in varIdxes:
  175. if varIdx == NO_VARIATION_INDEX:
  176. continue
  177. major = varIdx >> 16
  178. minor = varIdx & 0xFFFF
  179. d = used.get(major)
  180. if d is None:
  181. d = used[major] = set()
  182. d.add(minor)
  183. del varIdxes
  184. #
  185. # Subset VarData
  186. #
  187. varData = self.VarData
  188. newVarData = []
  189. varDataMap = {NO_VARIATION_INDEX: NO_VARIATION_INDEX}
  190. for major, data in enumerate(varData):
  191. usedMinors = used.get(major)
  192. if usedMinors is None:
  193. continue
  194. newMajor = len(newVarData)
  195. newVarData.append(data)
  196. items = data.Item
  197. newItems = []
  198. if major == 0 and retainFirstMap:
  199. for minor in range(len(items)):
  200. newItems.append(
  201. items[minor] if minor in usedMinors else [0] * len(items[minor])
  202. )
  203. varDataMap[minor] = minor
  204. else:
  205. if major == 0:
  206. minors = sorted(advIdxes) + sorted(usedMinors - advIdxes)
  207. else:
  208. minors = sorted(usedMinors)
  209. for minor in minors:
  210. newMinor = len(newItems)
  211. newItems.append(items[minor])
  212. varDataMap[(major << 16) + minor] = (newMajor << 16) + newMinor
  213. data.Item = newItems
  214. data.ItemCount = len(data.Item)
  215. data.calculateNumShorts(optimize=optimize)
  216. self.VarData = newVarData
  217. self.VarDataCount = len(self.VarData)
  218. self.prune_regions()
  219. return varDataMap
  220. ot.VarStore.subset_varidxes = VarStore_subset_varidxes
  221. def VarStore_prune_regions(self):
  222. """Remove unused VarRegions."""
  223. #
  224. # Subset VarRegionList
  225. #
  226. # Collect.
  227. usedRegions = set()
  228. for data in self.VarData:
  229. usedRegions.update(data.VarRegionIndex)
  230. # Subset.
  231. regionList = self.VarRegionList
  232. regions = regionList.Region
  233. newRegions = []
  234. regionMap = {}
  235. for i in sorted(usedRegions):
  236. regionMap[i] = len(newRegions)
  237. newRegions.append(regions[i])
  238. regionList.Region = newRegions
  239. regionList.RegionCount = len(regionList.Region)
  240. # Map.
  241. for data in self.VarData:
  242. data.VarRegionIndex = [regionMap[i] for i in data.VarRegionIndex]
  243. ot.VarStore.prune_regions = VarStore_prune_regions
  244. def _visit(self, func):
  245. """Recurse down from self, if type of an object is ot.Device,
  246. call func() on it. Works on otData-style classes."""
  247. if type(self) == ot.Device:
  248. func(self)
  249. elif isinstance(self, list):
  250. for that in self:
  251. _visit(that, func)
  252. elif hasattr(self, "getConverters") and not hasattr(self, "postRead"):
  253. for conv in self.getConverters():
  254. that = getattr(self, conv.name, None)
  255. if that is not None:
  256. _visit(that, func)
  257. elif isinstance(self, ot.ValueRecord):
  258. for that in self.__dict__.values():
  259. _visit(that, func)
  260. def _Device_recordVarIdx(self, s):
  261. """Add VarIdx in this Device table (if any) to the set s."""
  262. if self.DeltaFormat == 0x8000:
  263. s.add((self.StartSize << 16) + self.EndSize)
  264. def Object_collect_device_varidxes(self, varidxes):
  265. adder = partial(_Device_recordVarIdx, s=varidxes)
  266. _visit(self, adder)
  267. ot.GDEF.collect_device_varidxes = Object_collect_device_varidxes
  268. ot.GPOS.collect_device_varidxes = Object_collect_device_varidxes
  269. def _Device_mapVarIdx(self, mapping, done):
  270. """Map VarIdx in this Device table (if any) through mapping."""
  271. if id(self) in done:
  272. return
  273. done.add(id(self))
  274. if self.DeltaFormat == 0x8000:
  275. varIdx = mapping[(self.StartSize << 16) + self.EndSize]
  276. self.StartSize = varIdx >> 16
  277. self.EndSize = varIdx & 0xFFFF
  278. def Object_remap_device_varidxes(self, varidxes_map):
  279. mapper = partial(_Device_mapVarIdx, mapping=varidxes_map, done=set())
  280. _visit(self, mapper)
  281. ot.GDEF.remap_device_varidxes = Object_remap_device_varidxes
  282. ot.GPOS.remap_device_varidxes = Object_remap_device_varidxes
  283. class _Encoding(object):
  284. def __init__(self, chars):
  285. self.chars = chars
  286. self.width = bit_count(chars)
  287. self.columns = self._columns(chars)
  288. self.overhead = self._characteristic_overhead(self.columns)
  289. self.items = set()
  290. def append(self, row):
  291. self.items.add(row)
  292. def extend(self, lst):
  293. self.items.update(lst)
  294. def get_room(self):
  295. """Maximum number of bytes that can be added to characteristic
  296. while still being beneficial to merge it into another one."""
  297. count = len(self.items)
  298. return max(0, (self.overhead - 1) // count - self.width)
  299. room = property(get_room)
  300. def get_gain(self):
  301. """Maximum possible byte gain from merging this into another
  302. characteristic."""
  303. count = len(self.items)
  304. return max(0, self.overhead - count)
  305. gain = property(get_gain)
  306. def gain_sort_key(self):
  307. return self.gain, self.chars
  308. def width_sort_key(self):
  309. return self.width, self.chars
  310. @staticmethod
  311. def _characteristic_overhead(columns):
  312. """Returns overhead in bytes of encoding this characteristic
  313. as a VarData."""
  314. c = 4 + 6 # 4 bytes for LOffset, 6 bytes for VarData header
  315. c += bit_count(columns) * 2
  316. return c
  317. @staticmethod
  318. def _columns(chars):
  319. cols = 0
  320. i = 1
  321. while chars:
  322. if chars & 0b1111:
  323. cols |= i
  324. chars >>= 4
  325. i <<= 1
  326. return cols
  327. def gain_from_merging(self, other_encoding):
  328. combined_chars = other_encoding.chars | self.chars
  329. combined_width = bit_count(combined_chars)
  330. combined_columns = self.columns | other_encoding.columns
  331. combined_overhead = _Encoding._characteristic_overhead(combined_columns)
  332. combined_gain = (
  333. +self.overhead
  334. + other_encoding.overhead
  335. - combined_overhead
  336. - (combined_width - self.width) * len(self.items)
  337. - (combined_width - other_encoding.width) * len(other_encoding.items)
  338. )
  339. return combined_gain
  340. class _EncodingDict(dict):
  341. def __missing__(self, chars):
  342. r = self[chars] = _Encoding(chars)
  343. return r
  344. def add_row(self, row):
  345. chars = self._row_characteristics(row)
  346. self[chars].append(row)
  347. @staticmethod
  348. def _row_characteristics(row):
  349. """Returns encoding characteristics for a row."""
  350. longWords = False
  351. chars = 0
  352. i = 1
  353. for v in row:
  354. if v:
  355. chars += i
  356. if not (-128 <= v <= 127):
  357. chars += i * 0b0010
  358. if not (-32768 <= v <= 32767):
  359. longWords = True
  360. break
  361. i <<= 4
  362. if longWords:
  363. # Redo; only allow 2byte/4byte encoding
  364. chars = 0
  365. i = 1
  366. for v in row:
  367. if v:
  368. chars += i * 0b0011
  369. if not (-32768 <= v <= 32767):
  370. chars += i * 0b1100
  371. i <<= 4
  372. return chars
  373. def VarStore_optimize(self, use_NO_VARIATION_INDEX=True, quantization=1):
  374. """Optimize storage. Returns mapping from old VarIdxes to new ones."""
  375. # Overview:
  376. #
  377. # For each VarData row, we first extend it with zeroes to have
  378. # one column per region in VarRegionList. We then group the
  379. # rows into _Encoding objects, by their "characteristic" bitmap.
  380. # The characteristic bitmap is a binary number representing how
  381. # many bytes each column of the data takes up to encode. Each
  382. # column is encoded in four bits. For example, if a column has
  383. # only values in the range -128..127, it would only have a single
  384. # bit set in the characteristic bitmap for that column. If it has
  385. # values in the range -32768..32767, it would have two bits set.
  386. # The number of ones in the characteristic bitmap is the "width"
  387. # of the encoding.
  388. #
  389. # Each encoding as such has a number of "active" (ie. non-zero)
  390. # columns. The overhead of encoding the characteristic bitmap
  391. # is 10 bytes, plus 2 bytes per active column.
  392. #
  393. # When an encoding is merged into another one, if the characteristic
  394. # of the old encoding is a subset of the new one, then the overhead
  395. # of the old encoding is completely eliminated. However, each row
  396. # now would require more bytes to encode, to the tune of one byte
  397. # per characteristic bit that is active in the new encoding but not
  398. # in the old one. The number of bits that can be added to an encoding
  399. # while still beneficial to merge it into another encoding is called
  400. # the "room" for that encoding.
  401. #
  402. # The "gain" of an encodings is the maximum number of bytes we can
  403. # save by merging it into another encoding. The "gain" of merging
  404. # two encodings is how many bytes we save by doing so.
  405. #
  406. # High-level algorithm:
  407. #
  408. # - Each encoding has a minimal way to encode it. However, because
  409. # of the overhead of encoding the characteristic bitmap, it may
  410. # be beneficial to merge two encodings together, if there is
  411. # gain in doing so. As such, we need to search for the best
  412. # such successive merges.
  413. #
  414. # Algorithm:
  415. #
  416. # - Put all encodings into a "todo" list.
  417. #
  418. # - Sort todo list by decreasing gain (for stability).
  419. #
  420. # - Make a priority-queue of the gain from combining each two
  421. # encodings in the todo list. The priority queue is sorted by
  422. # decreasing gain. Only positive gains are included.
  423. #
  424. # - While priority queue is not empty:
  425. # - Pop the first item from the priority queue,
  426. # - Merge the two encodings it represents,
  427. # - Remove the two encodings from the todo list,
  428. # - Insert positive gains from combining the new encoding with
  429. # all existing todo list items into the priority queue,
  430. # - If a todo list item with the same characteristic bitmap as
  431. # the new encoding exists, remove it from the todo list and
  432. # merge it into the new encoding.
  433. # - Insert the new encoding into the todo list,
  434. #
  435. # - Encode all remaining items in the todo list.
  436. #
  437. # The output is then sorted for stability, in the following way:
  438. # - The VarRegionList of the input is kept intact.
  439. # - All encodings are sorted before the main algorithm, by
  440. # gain_key_sort(), which is a tuple of the following items:
  441. # * The gain of the encoding.
  442. # * The characteristic bitmap of the encoding, with higher-numbered
  443. # columns compared first.
  444. # - The VarData is sorted by width_sort_key(), which is a tuple
  445. # of the following items:
  446. # * The "width" of the encoding.
  447. # * The characteristic bitmap of the encoding, with higher-numbered
  448. # columns compared first.
  449. # - Within each VarData, the items are sorted as vectors of numbers.
  450. #
  451. # Finally, each VarData is optimized to remove the empty columns and
  452. # reorder columns as needed.
  453. # TODO
  454. # Check that no two VarRegions are the same; if they are, fold them.
  455. n = len(self.VarRegionList.Region) # Number of columns
  456. zeroes = [0] * n
  457. front_mapping = {} # Map from old VarIdxes to full row tuples
  458. encodings = _EncodingDict()
  459. # Collect all items into a set of full rows (with lots of zeroes.)
  460. for major, data in enumerate(self.VarData):
  461. regionIndices = data.VarRegionIndex
  462. for minor, item in enumerate(data.Item):
  463. row = list(zeroes)
  464. if quantization == 1:
  465. for regionIdx, v in zip(regionIndices, item):
  466. row[regionIdx] += v
  467. else:
  468. for regionIdx, v in zip(regionIndices, item):
  469. row[regionIdx] += (
  470. round(v / quantization) * quantization
  471. ) # TODO https://github.com/fonttools/fonttools/pull/3126#discussion_r1205439785
  472. row = tuple(row)
  473. if use_NO_VARIATION_INDEX and not any(row):
  474. front_mapping[(major << 16) + minor] = None
  475. continue
  476. encodings.add_row(row)
  477. front_mapping[(major << 16) + minor] = row
  478. # Prepare for the main algorithm.
  479. todo = sorted(encodings.values(), key=_Encoding.gain_sort_key)
  480. del encodings
  481. # Repeatedly pick two best encodings to combine, and combine them.
  482. heap = []
  483. for i, encoding in enumerate(todo):
  484. for j in range(i + 1, len(todo)):
  485. other_encoding = todo[j]
  486. combining_gain = encoding.gain_from_merging(other_encoding)
  487. if combining_gain > 0:
  488. heappush(heap, (-combining_gain, i, j))
  489. while heap:
  490. _, i, j = heappop(heap)
  491. if todo[i] is None or todo[j] is None:
  492. continue
  493. encoding, other_encoding = todo[i], todo[j]
  494. todo[i], todo[j] = None, None
  495. # Combine the two encodings
  496. combined_chars = other_encoding.chars | encoding.chars
  497. combined_encoding = _Encoding(combined_chars)
  498. combined_encoding.extend(encoding.items)
  499. combined_encoding.extend(other_encoding.items)
  500. for k, enc in enumerate(todo):
  501. if enc is None:
  502. continue
  503. # In the unlikely event that the same encoding exists already,
  504. # combine it.
  505. if enc.chars == combined_chars:
  506. combined_encoding.extend(enc.items)
  507. todo[k] = None
  508. continue
  509. combining_gain = combined_encoding.gain_from_merging(enc)
  510. if combining_gain > 0:
  511. heappush(heap, (-combining_gain, k, len(todo)))
  512. todo.append(combined_encoding)
  513. encodings = [encoding for encoding in todo if encoding is not None]
  514. # Assemble final store.
  515. back_mapping = {} # Mapping from full rows to new VarIdxes
  516. encodings.sort(key=_Encoding.width_sort_key)
  517. self.VarData = []
  518. for encoding in encodings:
  519. items = sorted(encoding.items)
  520. while items:
  521. major = len(self.VarData)
  522. data = ot.VarData()
  523. self.VarData.append(data)
  524. data.VarRegionIndex = range(n)
  525. data.VarRegionCount = len(data.VarRegionIndex)
  526. # Each major can only encode up to 0xFFFF entries.
  527. data.Item, items = items[:0xFFFF], items[0xFFFF:]
  528. for minor, item in enumerate(data.Item):
  529. back_mapping[item] = (major << 16) + minor
  530. # Compile final mapping.
  531. varidx_map = {NO_VARIATION_INDEX: NO_VARIATION_INDEX}
  532. for k, v in front_mapping.items():
  533. varidx_map[k] = back_mapping[v] if v is not None else NO_VARIATION_INDEX
  534. # Recalculate things and go home.
  535. self.VarRegionList.RegionCount = len(self.VarRegionList.Region)
  536. self.VarDataCount = len(self.VarData)
  537. for data in self.VarData:
  538. data.ItemCount = len(data.Item)
  539. data.optimize()
  540. # Remove unused regions.
  541. self.prune_regions()
  542. return varidx_map
  543. ot.VarStore.optimize = VarStore_optimize
  544. def main(args=None):
  545. """Optimize a font's GDEF variation store"""
  546. from argparse import ArgumentParser
  547. from fontTools import configLogger
  548. from fontTools.ttLib import TTFont
  549. from fontTools.ttLib.tables.otBase import OTTableWriter
  550. parser = ArgumentParser(prog="varLib.varStore", description=main.__doc__)
  551. parser.add_argument("--quantization", type=int, default=1)
  552. parser.add_argument("fontfile")
  553. parser.add_argument("outfile", nargs="?")
  554. options = parser.parse_args(args)
  555. # TODO: allow user to configure logging via command-line options
  556. configLogger(level="INFO")
  557. quantization = options.quantization
  558. fontfile = options.fontfile
  559. outfile = options.outfile
  560. font = TTFont(fontfile)
  561. gdef = font["GDEF"]
  562. store = gdef.table.VarStore
  563. writer = OTTableWriter()
  564. store.compile(writer, font)
  565. size = len(writer.getAllData())
  566. print("Before: %7d bytes" % size)
  567. varidx_map = store.optimize(quantization=quantization)
  568. writer = OTTableWriter()
  569. store.compile(writer, font)
  570. size = len(writer.getAllData())
  571. print("After: %7d bytes" % size)
  572. if outfile is not None:
  573. gdef.table.remap_device_varidxes(varidx_map)
  574. if "GPOS" in font:
  575. font["GPOS"].table.remap_device_varidxes(varidx_map)
  576. font.save(outfile)
  577. if __name__ == "__main__":
  578. import sys
  579. if len(sys.argv) > 1:
  580. sys.exit(main())
  581. import doctest
  582. sys.exit(doctest.testmod().failed)