cff.py 22 KB

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