cff.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. from collections import namedtuple
  2. from fontTools.cffLib import (
  3. maxStackLimit,
  4. TopDictIndex,
  5. buildOrder,
  6. topDictOperators,
  7. topDictOperators2,
  8. privateDictOperators,
  9. privateDictOperators2,
  10. FDArrayIndex,
  11. FontDict,
  12. VarStoreData,
  13. )
  14. from io import BytesIO
  15. from fontTools.cffLib.specializer import specializeCommands, commandsToProgram
  16. from fontTools.ttLib import newTable
  17. from fontTools import varLib
  18. from fontTools.varLib.models import allEqual
  19. from fontTools.misc.roundTools import roundFunc
  20. from fontTools.misc.psCharStrings import T2CharString, T2OutlineExtractor
  21. from fontTools.pens.t2CharStringPen import T2CharStringPen
  22. from functools import partial
  23. from .errors import (
  24. VarLibCFFDictMergeError,
  25. VarLibCFFPointTypeMergeError,
  26. VarLibCFFHintTypeMergeError,
  27. VarLibMergeError,
  28. )
  29. # Backwards compatibility
  30. MergeDictError = VarLibCFFDictMergeError
  31. MergeTypeError = VarLibCFFPointTypeMergeError
  32. def addCFFVarStore(varFont, varModel, varDataList, masterSupports):
  33. fvarTable = varFont["fvar"]
  34. axisKeys = [axis.axisTag for axis in fvarTable.axes]
  35. varTupleList = varLib.builder.buildVarRegionList(masterSupports, axisKeys)
  36. varStoreCFFV = varLib.builder.buildVarStore(varTupleList, varDataList)
  37. topDict = varFont["CFF2"].cff.topDictIndex[0]
  38. topDict.VarStore = VarStoreData(otVarStore=varStoreCFFV)
  39. if topDict.FDArray[0].vstore is None:
  40. fdArray = topDict.FDArray
  41. for fontDict in fdArray:
  42. if hasattr(fontDict, "Private"):
  43. fontDict.Private.vstore = topDict.VarStore
  44. def lib_convertCFFToCFF2(cff, otFont):
  45. # This assumes a decompiled CFF table.
  46. cff2GetGlyphOrder = cff.otFont.getGlyphOrder
  47. topDictData = TopDictIndex(None, cff2GetGlyphOrder, None)
  48. topDictData.items = cff.topDictIndex.items
  49. cff.topDictIndex = topDictData
  50. topDict = topDictData[0]
  51. if hasattr(topDict, "Private"):
  52. privateDict = topDict.Private
  53. else:
  54. privateDict = None
  55. opOrder = buildOrder(topDictOperators2)
  56. topDict.order = opOrder
  57. topDict.cff2GetGlyphOrder = cff2GetGlyphOrder
  58. if not hasattr(topDict, "FDArray"):
  59. fdArray = topDict.FDArray = FDArrayIndex()
  60. fdArray.strings = None
  61. fdArray.GlobalSubrs = topDict.GlobalSubrs
  62. topDict.GlobalSubrs.fdArray = fdArray
  63. charStrings = topDict.CharStrings
  64. if charStrings.charStringsAreIndexed:
  65. charStrings.charStringsIndex.fdArray = fdArray
  66. else:
  67. charStrings.fdArray = fdArray
  68. fontDict = FontDict()
  69. fontDict.setCFF2(True)
  70. fdArray.append(fontDict)
  71. fontDict.Private = privateDict
  72. privateOpOrder = buildOrder(privateDictOperators2)
  73. if privateDict is not None:
  74. for entry in privateDictOperators:
  75. key = entry[1]
  76. if key not in privateOpOrder:
  77. if key in privateDict.rawDict:
  78. # print "Removing private dict", key
  79. del privateDict.rawDict[key]
  80. if hasattr(privateDict, key):
  81. delattr(privateDict, key)
  82. # print "Removing privateDict attr", key
  83. else:
  84. # clean up the PrivateDicts in the fdArray
  85. fdArray = topDict.FDArray
  86. privateOpOrder = buildOrder(privateDictOperators2)
  87. for fontDict in fdArray:
  88. fontDict.setCFF2(True)
  89. for key in list(fontDict.rawDict.keys()):
  90. if key not in fontDict.order:
  91. del fontDict.rawDict[key]
  92. if hasattr(fontDict, key):
  93. delattr(fontDict, key)
  94. privateDict = fontDict.Private
  95. for entry in privateDictOperators:
  96. key = entry[1]
  97. if key not in privateOpOrder:
  98. if key in privateDict.rawDict:
  99. # print "Removing private dict", key
  100. del privateDict.rawDict[key]
  101. if hasattr(privateDict, key):
  102. delattr(privateDict, key)
  103. # print "Removing privateDict attr", key
  104. # Now delete up the deprecated topDict operators from CFF 1.0
  105. for entry in topDictOperators:
  106. key = entry[1]
  107. if key not in opOrder:
  108. if key in topDict.rawDict:
  109. del topDict.rawDict[key]
  110. if hasattr(topDict, key):
  111. delattr(topDict, key)
  112. # At this point, the Subrs and Charstrings are all still T2Charstring class
  113. # easiest to fix this by compiling, then decompiling again
  114. cff.major = 2
  115. file = BytesIO()
  116. cff.compile(file, otFont, isCFF2=True)
  117. file.seek(0)
  118. cff.decompile(file, otFont, isCFF2=True)
  119. def convertCFFtoCFF2(varFont):
  120. # Convert base font to a single master CFF2 font.
  121. cffTable = varFont["CFF "]
  122. lib_convertCFFToCFF2(cffTable.cff, varFont)
  123. newCFF2 = newTable("CFF2")
  124. newCFF2.cff = cffTable.cff
  125. varFont["CFF2"] = newCFF2
  126. del varFont["CFF "]
  127. def conv_to_int(num):
  128. if isinstance(num, float) and num.is_integer():
  129. return int(num)
  130. return num
  131. pd_blend_fields = (
  132. "BlueValues",
  133. "OtherBlues",
  134. "FamilyBlues",
  135. "FamilyOtherBlues",
  136. "BlueScale",
  137. "BlueShift",
  138. "BlueFuzz",
  139. "StdHW",
  140. "StdVW",
  141. "StemSnapH",
  142. "StemSnapV",
  143. )
  144. def get_private(regionFDArrays, fd_index, ri, fd_map):
  145. region_fdArray = regionFDArrays[ri]
  146. region_fd_map = fd_map[fd_index]
  147. if ri in region_fd_map:
  148. region_fdIndex = region_fd_map[ri]
  149. private = region_fdArray[region_fdIndex].Private
  150. else:
  151. private = None
  152. return private
  153. def merge_PrivateDicts(top_dicts, vsindex_dict, var_model, fd_map):
  154. """
  155. I step through the FontDicts in the FDArray of the varfont TopDict.
  156. For each varfont FontDict:
  157. * step through each key in FontDict.Private.
  158. * For each key, step through each relevant source font Private dict, and
  159. build a list of values to blend.
  160. The 'relevant' source fonts are selected by first getting the right
  161. submodel using ``vsindex_dict[vsindex]``. The indices of the
  162. ``subModel.locations`` are mapped to source font list indices by
  163. assuming the latter order is the same as the order of the
  164. ``var_model.locations``. I can then get the index of each subModel
  165. location in the list of ``var_model.locations``.
  166. """
  167. topDict = top_dicts[0]
  168. region_top_dicts = top_dicts[1:]
  169. if hasattr(region_top_dicts[0], "FDArray"):
  170. regionFDArrays = [fdTopDict.FDArray for fdTopDict in region_top_dicts]
  171. else:
  172. regionFDArrays = [[fdTopDict] for fdTopDict in region_top_dicts]
  173. for fd_index, font_dict in enumerate(topDict.FDArray):
  174. private_dict = font_dict.Private
  175. vsindex = getattr(private_dict, "vsindex", 0)
  176. # At the moment, no PrivateDict has a vsindex key, but let's support
  177. # how it should work. See comment at end of
  178. # merge_charstrings() - still need to optimize use of vsindex.
  179. sub_model, _ = vsindex_dict[vsindex]
  180. master_indices = []
  181. for loc in sub_model.locations[1:]:
  182. i = var_model.locations.index(loc) - 1
  183. master_indices.append(i)
  184. pds = [private_dict]
  185. last_pd = private_dict
  186. for ri in master_indices:
  187. pd = get_private(regionFDArrays, fd_index, ri, fd_map)
  188. # If the region font doesn't have this FontDict, just reference
  189. # the last one used.
  190. if pd is None:
  191. pd = last_pd
  192. else:
  193. last_pd = pd
  194. pds.append(pd)
  195. num_masters = len(pds)
  196. for key, value in private_dict.rawDict.items():
  197. dataList = []
  198. if key not in pd_blend_fields:
  199. continue
  200. if isinstance(value, list):
  201. try:
  202. values = [pd.rawDict[key] for pd in pds]
  203. except KeyError:
  204. print(
  205. "Warning: {key} in default font Private dict is "
  206. "missing from another font, and was "
  207. "discarded.".format(key=key)
  208. )
  209. continue
  210. try:
  211. values = zip(*values)
  212. except IndexError:
  213. raise VarLibCFFDictMergeError(key, value, values)
  214. """
  215. Row 0 contains the first value from each master.
  216. Convert each row from absolute values to relative
  217. values from the previous row.
  218. e.g for three masters, a list of values was:
  219. master 0 OtherBlues = [-217,-205]
  220. master 1 OtherBlues = [-234,-222]
  221. master 1 OtherBlues = [-188,-176]
  222. The call to zip() converts this to:
  223. [(-217, -234, -188), (-205, -222, -176)]
  224. and is converted finally to:
  225. OtherBlues = [[-217, 17.0, 46.0], [-205, 0.0, 0.0]]
  226. """
  227. prev_val_list = [0] * num_masters
  228. any_points_differ = False
  229. for val_list in values:
  230. rel_list = [
  231. (val - prev_val_list[i]) for (i, val) in enumerate(val_list)
  232. ]
  233. if (not any_points_differ) and not allEqual(rel_list):
  234. any_points_differ = True
  235. prev_val_list = val_list
  236. deltas = sub_model.getDeltas(rel_list)
  237. # For PrivateDict BlueValues, the default font
  238. # values are absolute, not relative to the prior value.
  239. deltas[0] = val_list[0]
  240. dataList.append(deltas)
  241. # If there are no blend values,then
  242. # we can collapse the blend lists.
  243. if not any_points_differ:
  244. dataList = [data[0] for data in dataList]
  245. else:
  246. values = [pd.rawDict[key] for pd in pds]
  247. if not allEqual(values):
  248. dataList = sub_model.getDeltas(values)
  249. else:
  250. dataList = values[0]
  251. # Convert numbers with no decimal part to an int
  252. if isinstance(dataList, list):
  253. for i, item in enumerate(dataList):
  254. if isinstance(item, list):
  255. for j, jtem in enumerate(item):
  256. dataList[i][j] = conv_to_int(jtem)
  257. else:
  258. dataList[i] = conv_to_int(item)
  259. else:
  260. dataList = conv_to_int(dataList)
  261. private_dict.rawDict[key] = dataList
  262. def _cff_or_cff2(font):
  263. if "CFF " in font:
  264. return font["CFF "]
  265. return font["CFF2"]
  266. def getfd_map(varFont, fonts_list):
  267. """Since a subset source font may have fewer FontDicts in their
  268. FDArray than the default font, we have to match up the FontDicts in
  269. the different fonts . We do this with the FDSelect array, and by
  270. assuming that the same glyph will reference matching FontDicts in
  271. each source font. We return a mapping from fdIndex in the default
  272. font to a dictionary which maps each master list index of each
  273. region font to the equivalent fdIndex in the region font."""
  274. fd_map = {}
  275. default_font = fonts_list[0]
  276. region_fonts = fonts_list[1:]
  277. num_regions = len(region_fonts)
  278. topDict = _cff_or_cff2(default_font).cff.topDictIndex[0]
  279. if not hasattr(topDict, "FDSelect"):
  280. # All glyphs reference only one FontDict.
  281. # Map the FD index for regions to index 0.
  282. fd_map[0] = {ri: 0 for ri in range(num_regions)}
  283. return fd_map
  284. gname_mapping = {}
  285. default_fdSelect = topDict.FDSelect
  286. glyphOrder = default_font.getGlyphOrder()
  287. for gid, fdIndex in enumerate(default_fdSelect):
  288. gname_mapping[glyphOrder[gid]] = fdIndex
  289. if fdIndex not in fd_map:
  290. fd_map[fdIndex] = {}
  291. for ri, region_font in enumerate(region_fonts):
  292. region_glyphOrder = region_font.getGlyphOrder()
  293. region_topDict = _cff_or_cff2(region_font).cff.topDictIndex[0]
  294. if not hasattr(region_topDict, "FDSelect"):
  295. # All the glyphs share the same FontDict. Pick any glyph.
  296. default_fdIndex = gname_mapping[region_glyphOrder[0]]
  297. fd_map[default_fdIndex][ri] = 0
  298. else:
  299. region_fdSelect = region_topDict.FDSelect
  300. for gid, fdIndex in enumerate(region_fdSelect):
  301. default_fdIndex = gname_mapping[region_glyphOrder[gid]]
  302. region_map = fd_map[default_fdIndex]
  303. if ri not in region_map:
  304. region_map[ri] = fdIndex
  305. return fd_map
  306. CVarData = namedtuple("CVarData", "varDataList masterSupports vsindex_dict")
  307. def merge_region_fonts(varFont, model, ordered_fonts_list, glyphOrder):
  308. topDict = varFont["CFF2"].cff.topDictIndex[0]
  309. top_dicts = [topDict] + [
  310. _cff_or_cff2(ttFont).cff.topDictIndex[0] for ttFont in ordered_fonts_list[1:]
  311. ]
  312. num_masters = len(model.mapping)
  313. cvData = merge_charstrings(glyphOrder, num_masters, top_dicts, model)
  314. fd_map = getfd_map(varFont, ordered_fonts_list)
  315. merge_PrivateDicts(top_dicts, cvData.vsindex_dict, model, fd_map)
  316. addCFFVarStore(varFont, model, cvData.varDataList, cvData.masterSupports)
  317. def _get_cs(charstrings, glyphName, filterEmpty=False):
  318. if glyphName not in charstrings:
  319. return None
  320. cs = charstrings[glyphName]
  321. if filterEmpty:
  322. cs.decompile()
  323. if cs.program == []: # CFF2 empty charstring
  324. return None
  325. elif (
  326. len(cs.program) <= 2
  327. and cs.program[-1] == "endchar"
  328. and (len(cs.program) == 1 or type(cs.program[0]) in (int, float))
  329. ): # CFF1 empty charstring
  330. return None
  331. return cs
  332. def _add_new_vsindex(
  333. model, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList
  334. ):
  335. varTupleIndexes = []
  336. for support in model.supports[1:]:
  337. if support not in masterSupports:
  338. masterSupports.append(support)
  339. varTupleIndexes.append(masterSupports.index(support))
  340. var_data = varLib.builder.buildVarData(varTupleIndexes, None, False)
  341. vsindex = len(vsindex_dict)
  342. vsindex_by_key[key] = vsindex
  343. vsindex_dict[vsindex] = (model, [key])
  344. varDataList.append(var_data)
  345. return vsindex
  346. def merge_charstrings(glyphOrder, num_masters, top_dicts, masterModel):
  347. vsindex_dict = {}
  348. vsindex_by_key = {}
  349. varDataList = []
  350. masterSupports = []
  351. default_charstrings = top_dicts[0].CharStrings
  352. for gid, gname in enumerate(glyphOrder):
  353. # interpret empty non-default masters as missing glyphs from a sparse master
  354. all_cs = [
  355. _get_cs(td.CharStrings, gname, i != 0) for i, td in enumerate(top_dicts)
  356. ]
  357. model, model_cs = masterModel.getSubModel(all_cs)
  358. # create the first pass CFF2 charstring, from
  359. # the default charstring.
  360. default_charstring = model_cs[0]
  361. var_pen = CFF2CharStringMergePen([], gname, num_masters, 0)
  362. # We need to override outlineExtractor because these
  363. # charstrings do have widths in the 'program'; we need to drop these
  364. # values rather than post assertion error for them.
  365. default_charstring.outlineExtractor = MergeOutlineExtractor
  366. default_charstring.draw(var_pen)
  367. # Add the coordinates from all the other regions to the
  368. # blend lists in the CFF2 charstring.
  369. region_cs = model_cs[1:]
  370. for region_idx, region_charstring in enumerate(region_cs, start=1):
  371. var_pen.restart(region_idx)
  372. region_charstring.outlineExtractor = MergeOutlineExtractor
  373. region_charstring.draw(var_pen)
  374. # Collapse each coordinate list to a blend operator and its args.
  375. new_cs = var_pen.getCharString(
  376. private=default_charstring.private,
  377. globalSubrs=default_charstring.globalSubrs,
  378. var_model=model,
  379. optimize=True,
  380. )
  381. default_charstrings[gname] = new_cs
  382. if not region_cs:
  383. continue
  384. if (not var_pen.seen_moveto) or ("blend" not in new_cs.program):
  385. # If this is not a marking glyph, or if there are no blend
  386. # arguments, then we can use vsindex 0. No need to
  387. # check if we need a new vsindex.
  388. continue
  389. # If the charstring required a new model, create
  390. # a VarData table to go with, and set vsindex.
  391. key = tuple(v is not None for v in all_cs)
  392. try:
  393. vsindex = vsindex_by_key[key]
  394. except KeyError:
  395. vsindex = _add_new_vsindex(
  396. model, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList
  397. )
  398. # We do not need to check for an existing new_cs.private.vsindex,
  399. # as we know it doesn't exist yet.
  400. if vsindex != 0:
  401. new_cs.program[:0] = [vsindex, "vsindex"]
  402. # If there is no variation in any of the charstrings, then vsindex_dict
  403. # never gets built. This could still be needed if there is variation
  404. # in the PrivatDict, so we will build the default data for vsindex = 0.
  405. if not vsindex_dict:
  406. key = (True,) * num_masters
  407. _add_new_vsindex(
  408. masterModel, key, masterSupports, vsindex_dict, vsindex_by_key, varDataList
  409. )
  410. cvData = CVarData(
  411. varDataList=varDataList,
  412. masterSupports=masterSupports,
  413. vsindex_dict=vsindex_dict,
  414. )
  415. # XXX To do: optimize use of vsindex between the PrivateDicts and
  416. # charstrings
  417. return cvData
  418. class CFFToCFF2OutlineExtractor(T2OutlineExtractor):
  419. """This class is used to remove the initial width from the CFF
  420. charstring without trying to add the width to self.nominalWidthX,
  421. which is None."""
  422. def popallWidth(self, evenOdd=0):
  423. args = self.popall()
  424. if not self.gotWidth:
  425. if evenOdd ^ (len(args) % 2):
  426. args = args[1:]
  427. self.width = self.defaultWidthX
  428. self.gotWidth = 1
  429. return args
  430. class MergeOutlineExtractor(CFFToCFF2OutlineExtractor):
  431. """Used to extract the charstring commands - including hints - from a
  432. CFF charstring in order to merge it as another set of region data
  433. into a CFF2 variable font charstring."""
  434. def __init__(
  435. self,
  436. pen,
  437. localSubrs,
  438. globalSubrs,
  439. nominalWidthX,
  440. defaultWidthX,
  441. private=None,
  442. blender=None,
  443. ):
  444. super().__init__(
  445. pen, localSubrs, globalSubrs, nominalWidthX, defaultWidthX, private, blender
  446. )
  447. def countHints(self):
  448. args = self.popallWidth()
  449. self.hintCount = self.hintCount + len(args) // 2
  450. return args
  451. def _hint_op(self, type, args):
  452. self.pen.add_hint(type, args)
  453. def op_hstem(self, index):
  454. args = self.countHints()
  455. self._hint_op("hstem", args)
  456. def op_vstem(self, index):
  457. args = self.countHints()
  458. self._hint_op("vstem", args)
  459. def op_hstemhm(self, index):
  460. args = self.countHints()
  461. self._hint_op("hstemhm", args)
  462. def op_vstemhm(self, index):
  463. args = self.countHints()
  464. self._hint_op("vstemhm", args)
  465. def _get_hintmask(self, index):
  466. if not self.hintMaskBytes:
  467. args = self.countHints()
  468. if args:
  469. self._hint_op("vstemhm", args)
  470. self.hintMaskBytes = (self.hintCount + 7) // 8
  471. hintMaskBytes, index = self.callingStack[-1].getBytes(index, self.hintMaskBytes)
  472. return index, hintMaskBytes
  473. def op_hintmask(self, index):
  474. index, hintMaskBytes = self._get_hintmask(index)
  475. self.pen.add_hintmask("hintmask", [hintMaskBytes])
  476. return hintMaskBytes, index
  477. def op_cntrmask(self, index):
  478. index, hintMaskBytes = self._get_hintmask(index)
  479. self.pen.add_hintmask("cntrmask", [hintMaskBytes])
  480. return hintMaskBytes, index
  481. class CFF2CharStringMergePen(T2CharStringPen):
  482. """Pen to merge Type 2 CharStrings."""
  483. def __init__(
  484. self, default_commands, glyphName, num_masters, master_idx, roundTolerance=0.01
  485. ):
  486. # For roundTolerance see https://github.com/fonttools/fonttools/issues/2838
  487. super().__init__(
  488. width=None, glyphSet=None, CFF2=True, roundTolerance=roundTolerance
  489. )
  490. self.pt_index = 0
  491. self._commands = default_commands
  492. self.m_index = master_idx
  493. self.num_masters = num_masters
  494. self.prev_move_idx = 0
  495. self.seen_moveto = False
  496. self.glyphName = glyphName
  497. self.round = roundFunc(roundTolerance, round=round)
  498. def add_point(self, point_type, pt_coords):
  499. if self.m_index == 0:
  500. self._commands.append([point_type, [pt_coords]])
  501. else:
  502. cmd = self._commands[self.pt_index]
  503. if cmd[0] != point_type:
  504. raise VarLibCFFPointTypeMergeError(
  505. point_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName
  506. )
  507. cmd[1].append(pt_coords)
  508. self.pt_index += 1
  509. def add_hint(self, hint_type, args):
  510. if self.m_index == 0:
  511. self._commands.append([hint_type, [args]])
  512. else:
  513. cmd = self._commands[self.pt_index]
  514. if cmd[0] != hint_type:
  515. raise VarLibCFFHintTypeMergeError(
  516. hint_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName
  517. )
  518. cmd[1].append(args)
  519. self.pt_index += 1
  520. def add_hintmask(self, hint_type, abs_args):
  521. # For hintmask, fonttools.cffLib.specializer.py expects
  522. # each of these to be represented by two sequential commands:
  523. # first holding only the operator name, with an empty arg list,
  524. # second with an empty string as the op name, and the mask arg list.
  525. if self.m_index == 0:
  526. self._commands.append([hint_type, []])
  527. self._commands.append(["", [abs_args]])
  528. else:
  529. cmd = self._commands[self.pt_index]
  530. if cmd[0] != hint_type:
  531. raise VarLibCFFHintTypeMergeError(
  532. hint_type, self.pt_index, len(cmd[1]), cmd[0], self.glyphName
  533. )
  534. self.pt_index += 1
  535. cmd = self._commands[self.pt_index]
  536. cmd[1].append(abs_args)
  537. self.pt_index += 1
  538. def _moveTo(self, pt):
  539. if not self.seen_moveto:
  540. self.seen_moveto = True
  541. pt_coords = self._p(pt)
  542. self.add_point("rmoveto", pt_coords)
  543. # I set prev_move_idx here because add_point()
  544. # can change self.pt_index.
  545. self.prev_move_idx = self.pt_index - 1
  546. def _lineTo(self, pt):
  547. pt_coords = self._p(pt)
  548. self.add_point("rlineto", pt_coords)
  549. def _curveToOne(self, pt1, pt2, pt3):
  550. _p = self._p
  551. pt_coords = _p(pt1) + _p(pt2) + _p(pt3)
  552. self.add_point("rrcurveto", pt_coords)
  553. def _closePath(self):
  554. pass
  555. def _endPath(self):
  556. pass
  557. def restart(self, region_idx):
  558. self.pt_index = 0
  559. self.m_index = region_idx
  560. self._p0 = (0, 0)
  561. def getCommands(self):
  562. return self._commands
  563. def reorder_blend_args(self, commands, get_delta_func):
  564. """
  565. We first re-order the master coordinate values.
  566. For a moveto to lineto, the args are now arranged as::
  567. [ [master_0 x,y], [master_1 x,y], [master_2 x,y] ]
  568. We re-arrange this to::
  569. [ [master_0 x, master_1 x, master_2 x],
  570. [master_0 y, master_1 y, master_2 y]
  571. ]
  572. If the master values are all the same, we collapse the list to
  573. as single value instead of a list.
  574. We then convert this to::
  575. [ [master_0 x] + [x delta tuple] + [numBlends=1]
  576. [master_0 y] + [y delta tuple] + [numBlends=1]
  577. ]
  578. """
  579. for cmd in commands:
  580. # arg[i] is the set of arguments for this operator from master i.
  581. args = cmd[1]
  582. m_args = zip(*args)
  583. # m_args[n] is now all num_master args for the i'th argument
  584. # for this operation.
  585. cmd[1] = list(m_args)
  586. lastOp = None
  587. for cmd in commands:
  588. op = cmd[0]
  589. # masks are represented by two cmd's: first has only op names,
  590. # second has only args.
  591. if lastOp in ["hintmask", "cntrmask"]:
  592. coord = list(cmd[1])
  593. if not allEqual(coord):
  594. raise VarLibMergeError(
  595. "Hintmask values cannot differ between source fonts."
  596. )
  597. cmd[1] = [coord[0][0]]
  598. else:
  599. coords = cmd[1]
  600. new_coords = []
  601. for coord in coords:
  602. if allEqual(coord):
  603. new_coords.append(coord[0])
  604. else:
  605. # convert to deltas
  606. deltas = get_delta_func(coord)[1:]
  607. coord = [coord[0]] + deltas
  608. coord.append(1)
  609. new_coords.append(coord)
  610. cmd[1] = new_coords
  611. lastOp = op
  612. return commands
  613. def getCharString(
  614. self, private=None, globalSubrs=None, var_model=None, optimize=True
  615. ):
  616. commands = self._commands
  617. commands = self.reorder_blend_args(
  618. commands, partial(var_model.getDeltas, round=self.round)
  619. )
  620. if optimize:
  621. commands = specializeCommands(
  622. commands, generalizeFirst=False, maxstack=maxStackLimit
  623. )
  624. program = commandsToProgram(commands)
  625. charString = T2CharString(
  626. program=program, private=private, globalSubrs=globalSubrs
  627. )
  628. return charString