specializer.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847
  1. # -*- coding: utf-8 -*-
  2. """T2CharString operator specializer and generalizer.
  3. PostScript glyph drawing operations can be expressed in multiple different
  4. ways. For example, as well as the ``lineto`` operator, there is also a
  5. ``hlineto`` operator which draws a horizontal line, removing the need to
  6. specify a ``dx`` coordinate, and a ``vlineto`` operator which draws a
  7. vertical line, removing the need to specify a ``dy`` coordinate. As well
  8. as decompiling :class:`fontTools.misc.psCharStrings.T2CharString` objects
  9. into lists of operations, this module allows for conversion between general
  10. and specific forms of the operation.
  11. """
  12. from fontTools.cffLib import maxStackLimit
  13. def stringToProgram(string):
  14. if isinstance(string, str):
  15. string = string.split()
  16. program = []
  17. for token in string:
  18. try:
  19. token = int(token)
  20. except ValueError:
  21. try:
  22. token = float(token)
  23. except ValueError:
  24. pass
  25. program.append(token)
  26. return program
  27. def programToString(program):
  28. return " ".join(str(x) for x in program)
  29. def programToCommands(program, getNumRegions=None):
  30. """Takes a T2CharString program list and returns list of commands.
  31. Each command is a two-tuple of commandname,arg-list. The commandname might
  32. be empty string if no commandname shall be emitted (used for glyph width,
  33. hintmask/cntrmask argument, as well as stray arguments at the end of the
  34. program (🤷).
  35. 'getNumRegions' may be None, or a callable object. It must return the
  36. number of regions. 'getNumRegions' takes a single argument, vsindex. It
  37. returns the numRegions for the vsindex.
  38. The Charstring may or may not start with a width value. If the first
  39. non-blend operator has an odd number of arguments, then the first argument is
  40. a width, and is popped off. This is complicated with blend operators, as
  41. there may be more than one before the first hint or moveto operator, and each
  42. one reduces several arguments to just one list argument. We have to sum the
  43. number of arguments that are not part of the blend arguments, and all the
  44. 'numBlends' values. We could instead have said that by definition, if there
  45. is a blend operator, there is no width value, since CFF2 Charstrings don't
  46. have width values. I discussed this with Behdad, and we are allowing for an
  47. initial width value in this case because developers may assemble a CFF2
  48. charstring from CFF Charstrings, which could have width values.
  49. """
  50. seenWidthOp = False
  51. vsIndex = 0
  52. lenBlendStack = 0
  53. lastBlendIndex = 0
  54. commands = []
  55. stack = []
  56. it = iter(program)
  57. for token in it:
  58. if not isinstance(token, str):
  59. stack.append(token)
  60. continue
  61. if token == "blend":
  62. assert getNumRegions is not None
  63. numSourceFonts = 1 + getNumRegions(vsIndex)
  64. # replace the blend op args on the stack with a single list
  65. # containing all the blend op args.
  66. numBlends = stack[-1]
  67. numBlendArgs = numBlends * numSourceFonts + 1
  68. # replace first blend op by a list of the blend ops.
  69. stack[-numBlendArgs:] = [stack[-numBlendArgs:]]
  70. lenBlendStack += numBlends + len(stack) - 1
  71. lastBlendIndex = len(stack)
  72. # if a blend op exists, this is or will be a CFF2 charstring.
  73. continue
  74. elif token == "vsindex":
  75. vsIndex = stack[-1]
  76. assert type(vsIndex) is int
  77. elif (not seenWidthOp) and token in {
  78. "hstem",
  79. "hstemhm",
  80. "vstem",
  81. "vstemhm",
  82. "cntrmask",
  83. "hintmask",
  84. "hmoveto",
  85. "vmoveto",
  86. "rmoveto",
  87. "endchar",
  88. }:
  89. seenWidthOp = True
  90. parity = token in {"hmoveto", "vmoveto"}
  91. if lenBlendStack:
  92. # lenBlendStack has the number of args represented by the last blend
  93. # arg and all the preceding args. We need to now add the number of
  94. # args following the last blend arg.
  95. numArgs = lenBlendStack + len(stack[lastBlendIndex:])
  96. else:
  97. numArgs = len(stack)
  98. if numArgs and (numArgs % 2) ^ parity:
  99. width = stack.pop(0)
  100. commands.append(("", [width]))
  101. if token in {"hintmask", "cntrmask"}:
  102. if stack:
  103. commands.append(("", stack))
  104. commands.append((token, []))
  105. commands.append(("", [next(it)]))
  106. else:
  107. commands.append((token, stack))
  108. stack = []
  109. if stack:
  110. commands.append(("", stack))
  111. return commands
  112. def _flattenBlendArgs(args):
  113. token_list = []
  114. for arg in args:
  115. if isinstance(arg, list):
  116. token_list.extend(arg)
  117. token_list.append("blend")
  118. else:
  119. token_list.append(arg)
  120. return token_list
  121. def commandsToProgram(commands):
  122. """Takes a commands list as returned by programToCommands() and converts
  123. it back to a T2CharString program list."""
  124. program = []
  125. for op, args in commands:
  126. if any(isinstance(arg, list) for arg in args):
  127. args = _flattenBlendArgs(args)
  128. program.extend(args)
  129. if op:
  130. program.append(op)
  131. return program
  132. def _everyN(el, n):
  133. """Group the list el into groups of size n"""
  134. if len(el) % n != 0:
  135. raise ValueError(el)
  136. for i in range(0, len(el), n):
  137. yield el[i : i + n]
  138. class _GeneralizerDecombinerCommandsMap(object):
  139. @staticmethod
  140. def rmoveto(args):
  141. if len(args) != 2:
  142. raise ValueError(args)
  143. yield ("rmoveto", args)
  144. @staticmethod
  145. def hmoveto(args):
  146. if len(args) != 1:
  147. raise ValueError(args)
  148. yield ("rmoveto", [args[0], 0])
  149. @staticmethod
  150. def vmoveto(args):
  151. if len(args) != 1:
  152. raise ValueError(args)
  153. yield ("rmoveto", [0, args[0]])
  154. @staticmethod
  155. def rlineto(args):
  156. if not args:
  157. raise ValueError(args)
  158. for args in _everyN(args, 2):
  159. yield ("rlineto", args)
  160. @staticmethod
  161. def hlineto(args):
  162. if not args:
  163. raise ValueError(args)
  164. it = iter(args)
  165. try:
  166. while True:
  167. yield ("rlineto", [next(it), 0])
  168. yield ("rlineto", [0, next(it)])
  169. except StopIteration:
  170. pass
  171. @staticmethod
  172. def vlineto(args):
  173. if not args:
  174. raise ValueError(args)
  175. it = iter(args)
  176. try:
  177. while True:
  178. yield ("rlineto", [0, next(it)])
  179. yield ("rlineto", [next(it), 0])
  180. except StopIteration:
  181. pass
  182. @staticmethod
  183. def rrcurveto(args):
  184. if not args:
  185. raise ValueError(args)
  186. for args in _everyN(args, 6):
  187. yield ("rrcurveto", args)
  188. @staticmethod
  189. def hhcurveto(args):
  190. if len(args) < 4 or len(args) % 4 > 1:
  191. raise ValueError(args)
  192. if len(args) % 2 == 1:
  193. yield ("rrcurveto", [args[1], args[0], args[2], args[3], args[4], 0])
  194. args = args[5:]
  195. for args in _everyN(args, 4):
  196. yield ("rrcurveto", [args[0], 0, args[1], args[2], args[3], 0])
  197. @staticmethod
  198. def vvcurveto(args):
  199. if len(args) < 4 or len(args) % 4 > 1:
  200. raise ValueError(args)
  201. if len(args) % 2 == 1:
  202. yield ("rrcurveto", [args[0], args[1], args[2], args[3], 0, args[4]])
  203. args = args[5:]
  204. for args in _everyN(args, 4):
  205. yield ("rrcurveto", [0, args[0], args[1], args[2], 0, args[3]])
  206. @staticmethod
  207. def hvcurveto(args):
  208. if len(args) < 4 or len(args) % 8 not in {0, 1, 4, 5}:
  209. raise ValueError(args)
  210. last_args = None
  211. if len(args) % 2 == 1:
  212. lastStraight = len(args) % 8 == 5
  213. args, last_args = args[:-5], args[-5:]
  214. it = _everyN(args, 4)
  215. try:
  216. while True:
  217. args = next(it)
  218. yield ("rrcurveto", [args[0], 0, args[1], args[2], 0, args[3]])
  219. args = next(it)
  220. yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], 0])
  221. except StopIteration:
  222. pass
  223. if last_args:
  224. args = last_args
  225. if lastStraight:
  226. yield ("rrcurveto", [args[0], 0, args[1], args[2], args[4], args[3]])
  227. else:
  228. yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], args[4]])
  229. @staticmethod
  230. def vhcurveto(args):
  231. if len(args) < 4 or len(args) % 8 not in {0, 1, 4, 5}:
  232. raise ValueError(args)
  233. last_args = None
  234. if len(args) % 2 == 1:
  235. lastStraight = len(args) % 8 == 5
  236. args, last_args = args[:-5], args[-5:]
  237. it = _everyN(args, 4)
  238. try:
  239. while True:
  240. args = next(it)
  241. yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], 0])
  242. args = next(it)
  243. yield ("rrcurveto", [args[0], 0, args[1], args[2], 0, args[3]])
  244. except StopIteration:
  245. pass
  246. if last_args:
  247. args = last_args
  248. if lastStraight:
  249. yield ("rrcurveto", [0, args[0], args[1], args[2], args[3], args[4]])
  250. else:
  251. yield ("rrcurveto", [args[0], 0, args[1], args[2], args[4], args[3]])
  252. @staticmethod
  253. def rcurveline(args):
  254. if len(args) < 8 or len(args) % 6 != 2:
  255. raise ValueError(args)
  256. args, last_args = args[:-2], args[-2:]
  257. for args in _everyN(args, 6):
  258. yield ("rrcurveto", args)
  259. yield ("rlineto", last_args)
  260. @staticmethod
  261. def rlinecurve(args):
  262. if len(args) < 8 or len(args) % 2 != 0:
  263. raise ValueError(args)
  264. args, last_args = args[:-6], args[-6:]
  265. for args in _everyN(args, 2):
  266. yield ("rlineto", args)
  267. yield ("rrcurveto", last_args)
  268. def _convertBlendOpToArgs(blendList):
  269. # args is list of blend op args. Since we are supporting
  270. # recursive blend op calls, some of these args may also
  271. # be a list of blend op args, and need to be converted before
  272. # we convert the current list.
  273. if any([isinstance(arg, list) for arg in blendList]):
  274. args = [
  275. i
  276. for e in blendList
  277. for i in (_convertBlendOpToArgs(e) if isinstance(e, list) else [e])
  278. ]
  279. else:
  280. args = blendList
  281. # We now know that blendList contains a blend op argument list, even if
  282. # some of the args are lists that each contain a blend op argument list.
  283. # Convert from:
  284. # [default font arg sequence x0,...,xn] + [delta tuple for x0] + ... + [delta tuple for xn]
  285. # to:
  286. # [ [x0] + [delta tuple for x0],
  287. # ...,
  288. # [xn] + [delta tuple for xn] ]
  289. numBlends = args[-1]
  290. # Can't use args.pop() when the args are being used in a nested list
  291. # comprehension. See calling context
  292. args = args[:-1]
  293. numRegions = len(args) // numBlends - 1
  294. if not (numBlends * (numRegions + 1) == len(args)):
  295. raise ValueError(blendList)
  296. defaultArgs = [[arg] for arg in args[:numBlends]]
  297. deltaArgs = args[numBlends:]
  298. numDeltaValues = len(deltaArgs)
  299. deltaList = [
  300. deltaArgs[i : i + numRegions] for i in range(0, numDeltaValues, numRegions)
  301. ]
  302. blend_args = [a + b + [1] for a, b in zip(defaultArgs, deltaList)]
  303. return blend_args
  304. def generalizeCommands(commands, ignoreErrors=False):
  305. result = []
  306. mapping = _GeneralizerDecombinerCommandsMap
  307. for op, args in commands:
  308. # First, generalize any blend args in the arg list.
  309. if any([isinstance(arg, list) for arg in args]):
  310. try:
  311. args = [
  312. n
  313. for arg in args
  314. for n in (
  315. _convertBlendOpToArgs(arg) if isinstance(arg, list) else [arg]
  316. )
  317. ]
  318. except ValueError:
  319. if ignoreErrors:
  320. # Store op as data, such that consumers of commands do not have to
  321. # deal with incorrect number of arguments.
  322. result.append(("", args))
  323. result.append(("", [op]))
  324. else:
  325. raise
  326. func = getattr(mapping, op, None)
  327. if not func:
  328. result.append((op, args))
  329. continue
  330. try:
  331. for command in func(args):
  332. result.append(command)
  333. except ValueError:
  334. if ignoreErrors:
  335. # Store op as data, such that consumers of commands do not have to
  336. # deal with incorrect number of arguments.
  337. result.append(("", args))
  338. result.append(("", [op]))
  339. else:
  340. raise
  341. return result
  342. def generalizeProgram(program, getNumRegions=None, **kwargs):
  343. return commandsToProgram(
  344. generalizeCommands(programToCommands(program, getNumRegions), **kwargs)
  345. )
  346. def _categorizeVector(v):
  347. """
  348. Takes X,Y vector v and returns one of r, h, v, or 0 depending on which
  349. of X and/or Y are zero, plus tuple of nonzero ones. If both are zero,
  350. it returns a single zero still.
  351. >>> _categorizeVector((0,0))
  352. ('0', (0,))
  353. >>> _categorizeVector((1,0))
  354. ('h', (1,))
  355. >>> _categorizeVector((0,2))
  356. ('v', (2,))
  357. >>> _categorizeVector((1,2))
  358. ('r', (1, 2))
  359. """
  360. if not v[0]:
  361. if not v[1]:
  362. return "0", v[:1]
  363. else:
  364. return "v", v[1:]
  365. else:
  366. if not v[1]:
  367. return "h", v[:1]
  368. else:
  369. return "r", v
  370. def _mergeCategories(a, b):
  371. if a == "0":
  372. return b
  373. if b == "0":
  374. return a
  375. if a == b:
  376. return a
  377. return None
  378. def _negateCategory(a):
  379. if a == "h":
  380. return "v"
  381. if a == "v":
  382. return "h"
  383. assert a in "0r"
  384. return a
  385. def _convertToBlendCmds(args):
  386. # return a list of blend commands, and
  387. # the remaining non-blended args, if any.
  388. num_args = len(args)
  389. stack_use = 0
  390. new_args = []
  391. i = 0
  392. while i < num_args:
  393. arg = args[i]
  394. if not isinstance(arg, list):
  395. new_args.append(arg)
  396. i += 1
  397. stack_use += 1
  398. else:
  399. prev_stack_use = stack_use
  400. # The arg is a tuple of blend values.
  401. # These are each (master 0,delta 1..delta n, 1)
  402. # Combine as many successive tuples as we can,
  403. # up to the max stack limit.
  404. num_sources = len(arg) - 1
  405. blendlist = [arg]
  406. i += 1
  407. stack_use += 1 + num_sources # 1 for the num_blends arg
  408. while (i < num_args) and isinstance(args[i], list):
  409. blendlist.append(args[i])
  410. i += 1
  411. stack_use += num_sources
  412. if stack_use + num_sources > maxStackLimit:
  413. # if we are here, max stack is the CFF2 max stack.
  414. # I use the CFF2 max stack limit here rather than
  415. # the 'maxstack' chosen by the client, as the default
  416. # maxstack may have been used unintentionally. For all
  417. # the other operators, this just produces a little less
  418. # optimization, but here it puts a hard (and low) limit
  419. # on the number of source fonts that can be used.
  420. break
  421. # blendList now contains as many single blend tuples as can be
  422. # combined without exceeding the CFF2 stack limit.
  423. num_blends = len(blendlist)
  424. # append the 'num_blends' default font values
  425. blend_args = []
  426. for arg in blendlist:
  427. blend_args.append(arg[0])
  428. for arg in blendlist:
  429. assert arg[-1] == 1
  430. blend_args.extend(arg[1:-1])
  431. blend_args.append(num_blends)
  432. new_args.append(blend_args)
  433. stack_use = prev_stack_use + num_blends
  434. return new_args
  435. def _addArgs(a, b):
  436. if isinstance(b, list):
  437. if isinstance(a, list):
  438. if len(a) != len(b) or a[-1] != b[-1]:
  439. raise ValueError()
  440. return [_addArgs(va, vb) for va, vb in zip(a[:-1], b[:-1])] + [a[-1]]
  441. else:
  442. a, b = b, a
  443. if isinstance(a, list):
  444. assert a[-1] == 1
  445. return [_addArgs(a[0], b)] + a[1:]
  446. return a + b
  447. def specializeCommands(
  448. commands,
  449. ignoreErrors=False,
  450. generalizeFirst=True,
  451. preserveTopology=False,
  452. maxstack=48,
  453. ):
  454. # We perform several rounds of optimizations. They are carefully ordered and are:
  455. #
  456. # 0. Generalize commands.
  457. # This ensures that they are in our expected simple form, with each line/curve only
  458. # having arguments for one segment, and using the generic form (rlineto/rrcurveto).
  459. # If caller is sure the input is in this form, they can turn off generalization to
  460. # save time.
  461. #
  462. # 1. Combine successive rmoveto operations.
  463. #
  464. # 2. Specialize rmoveto/rlineto/rrcurveto operators into horizontal/vertical variants.
  465. # We specialize into some, made-up, variants as well, which simplifies following
  466. # passes.
  467. #
  468. # 3. Merge or delete redundant operations, to the extent requested.
  469. # OpenType spec declares point numbers in CFF undefined. As such, we happily
  470. # change topology. If client relies on point numbers (in GPOS anchors, or for
  471. # hinting purposes(what?)) they can turn this off.
  472. #
  473. # 4. Peephole optimization to revert back some of the h/v variants back into their
  474. # original "relative" operator (rline/rrcurveto) if that saves a byte.
  475. #
  476. # 5. Combine adjacent operators when possible, minding not to go over max stack size.
  477. #
  478. # 6. Resolve any remaining made-up operators into real operators.
  479. #
  480. # I have convinced myself that this produces optimal bytecode (except for, possibly
  481. # one byte each time maxstack size prohibits combining.) YMMV, but you'd be wrong. :-)
  482. # A dynamic-programming approach can do the same but would be significantly slower.
  483. #
  484. # 7. For any args which are blend lists, convert them to a blend command.
  485. # 0. Generalize commands.
  486. if generalizeFirst:
  487. commands = generalizeCommands(commands, ignoreErrors=ignoreErrors)
  488. else:
  489. commands = list(commands) # Make copy since we modify in-place later.
  490. # 1. Combine successive rmoveto operations.
  491. for i in range(len(commands) - 1, 0, -1):
  492. if "rmoveto" == commands[i][0] == commands[i - 1][0]:
  493. v1, v2 = commands[i - 1][1], commands[i][1]
  494. commands[i - 1] = ("rmoveto", [v1[0] + v2[0], v1[1] + v2[1]])
  495. del commands[i]
  496. # 2. Specialize rmoveto/rlineto/rrcurveto operators into horizontal/vertical variants.
  497. #
  498. # We, in fact, specialize into more, made-up, variants that special-case when both
  499. # X and Y components are zero. This simplifies the following optimization passes.
  500. # This case is rare, but OCD does not let me skip it.
  501. #
  502. # After this round, we will have four variants that use the following mnemonics:
  503. #
  504. # - 'r' for relative, ie. non-zero X and non-zero Y,
  505. # - 'h' for horizontal, ie. zero X and non-zero Y,
  506. # - 'v' for vertical, ie. non-zero X and zero Y,
  507. # - '0' for zeros, ie. zero X and zero Y.
  508. #
  509. # The '0' pseudo-operators are not part of the spec, but help simplify the following
  510. # optimization rounds. We resolve them at the end. So, after this, we will have four
  511. # moveto and four lineto variants:
  512. #
  513. # - 0moveto, 0lineto
  514. # - hmoveto, hlineto
  515. # - vmoveto, vlineto
  516. # - rmoveto, rlineto
  517. #
  518. # and sixteen curveto variants. For example, a '0hcurveto' operator means a curve
  519. # dx0,dy0,dx1,dy1,dx2,dy2,dx3,dy3 where dx0, dx1, and dy3 are zero but not dx3.
  520. # An 'rvcurveto' means dx3 is zero but not dx0,dy0,dy3.
  521. #
  522. # There are nine different variants of curves without the '0'. Those nine map exactly
  523. # to the existing curve variants in the spec: rrcurveto, and the four variants hhcurveto,
  524. # vvcurveto, hvcurveto, and vhcurveto each cover two cases, one with an odd number of
  525. # arguments and one without. Eg. an hhcurveto with an extra argument (odd number of
  526. # arguments) is in fact an rhcurveto. The operators in the spec are designed such that
  527. # all four of rhcurveto, rvcurveto, hrcurveto, and vrcurveto are encodable for one curve.
  528. #
  529. # Of the curve types with '0', the 00curveto is equivalent to a lineto variant. The rest
  530. # of the curve types with a 0 need to be encoded as a h or v variant. Ie. a '0' can be
  531. # thought of a "don't care" and can be used as either an 'h' or a 'v'. As such, we always
  532. # encode a number 0 as argument when we use a '0' variant. Later on, we can just substitute
  533. # the '0' with either 'h' or 'v' and it works.
  534. #
  535. # When we get to curve splines however, things become more complicated... XXX finish this.
  536. # There's one more complexity with splines. If one side of the spline is not horizontal or
  537. # vertical (or zero), ie. if it's 'r', then it limits which spline types we can encode.
  538. # Only hhcurveto and vvcurveto operators can encode a spline starting with 'r', and
  539. # only hvcurveto and vhcurveto operators can encode a spline ending with 'r'.
  540. # This limits our merge opportunities later.
  541. #
  542. for i in range(len(commands)):
  543. op, args = commands[i]
  544. if op in {"rmoveto", "rlineto"}:
  545. c, args = _categorizeVector(args)
  546. commands[i] = c + op[1:], args
  547. continue
  548. if op == "rrcurveto":
  549. c1, args1 = _categorizeVector(args[:2])
  550. c2, args2 = _categorizeVector(args[-2:])
  551. commands[i] = c1 + c2 + "curveto", args1 + args[2:4] + args2
  552. continue
  553. # 3. Merge or delete redundant operations, to the extent requested.
  554. #
  555. # TODO
  556. # A 0moveto that comes before all other path operations can be removed.
  557. # though I find conflicting evidence for this.
  558. #
  559. # TODO
  560. # "If hstem and vstem hints are both declared at the beginning of a
  561. # CharString, and this sequence is followed directly by the hintmask or
  562. # cntrmask operators, then the vstem hint operator (or, if applicable,
  563. # the vstemhm operator) need not be included."
  564. #
  565. # "The sequence and form of a CFF2 CharString program may be represented as:
  566. # {hs* vs* cm* hm* mt subpath}? {mt subpath}*"
  567. #
  568. # https://www.microsoft.com/typography/otspec/cff2charstr.htm#section3.1
  569. #
  570. # For Type2 CharStrings the sequence is:
  571. # w? {hs* vs* cm* hm* mt subpath}? {mt subpath}* endchar"
  572. # Some other redundancies change topology (point numbers).
  573. if not preserveTopology:
  574. for i in range(len(commands) - 1, -1, -1):
  575. op, args = commands[i]
  576. # A 00curveto is demoted to a (specialized) lineto.
  577. if op == "00curveto":
  578. assert len(args) == 4
  579. c, args = _categorizeVector(args[1:3])
  580. op = c + "lineto"
  581. commands[i] = op, args
  582. # and then...
  583. # A 0lineto can be deleted.
  584. if op == "0lineto":
  585. del commands[i]
  586. continue
  587. # Merge adjacent hlineto's and vlineto's.
  588. # In CFF2 charstrings from variable fonts, each
  589. # arg item may be a list of blendable values, one from
  590. # each source font.
  591. if i and op in {"hlineto", "vlineto"} and (op == commands[i - 1][0]):
  592. _, other_args = commands[i - 1]
  593. assert len(args) == 1 and len(other_args) == 1
  594. try:
  595. new_args = [_addArgs(args[0], other_args[0])]
  596. except ValueError:
  597. continue
  598. commands[i - 1] = (op, new_args)
  599. del commands[i]
  600. continue
  601. # 4. Peephole optimization to revert back some of the h/v variants back into their
  602. # original "relative" operator (rline/rrcurveto) if that saves a byte.
  603. for i in range(1, len(commands) - 1):
  604. op, args = commands[i]
  605. prv, nxt = commands[i - 1][0], commands[i + 1][0]
  606. if op in {"0lineto", "hlineto", "vlineto"} and prv == nxt == "rlineto":
  607. assert len(args) == 1
  608. args = [0, args[0]] if op[0] == "v" else [args[0], 0]
  609. commands[i] = ("rlineto", args)
  610. continue
  611. if op[2:] == "curveto" and len(args) == 5 and prv == nxt == "rrcurveto":
  612. assert (op[0] == "r") ^ (op[1] == "r")
  613. if op[0] == "v":
  614. pos = 0
  615. elif op[0] != "r":
  616. pos = 1
  617. elif op[1] == "v":
  618. pos = 4
  619. else:
  620. pos = 5
  621. # Insert, while maintaining the type of args (can be tuple or list).
  622. args = args[:pos] + type(args)((0,)) + args[pos:]
  623. commands[i] = ("rrcurveto", args)
  624. continue
  625. # 5. Combine adjacent operators when possible, minding not to go over max stack size.
  626. for i in range(len(commands) - 1, 0, -1):
  627. op1, args1 = commands[i - 1]
  628. op2, args2 = commands[i]
  629. new_op = None
  630. # Merge logic...
  631. if {op1, op2} <= {"rlineto", "rrcurveto"}:
  632. if op1 == op2:
  633. new_op = op1
  634. else:
  635. if op2 == "rrcurveto" and len(args2) == 6:
  636. new_op = "rlinecurve"
  637. elif len(args2) == 2:
  638. new_op = "rcurveline"
  639. elif (op1, op2) in {("rlineto", "rlinecurve"), ("rrcurveto", "rcurveline")}:
  640. new_op = op2
  641. elif {op1, op2} == {"vlineto", "hlineto"}:
  642. new_op = op1
  643. elif "curveto" == op1[2:] == op2[2:]:
  644. d0, d1 = op1[:2]
  645. d2, d3 = op2[:2]
  646. if d1 == "r" or d2 == "r" or d0 == d3 == "r":
  647. continue
  648. d = _mergeCategories(d1, d2)
  649. if d is None:
  650. continue
  651. if d0 == "r":
  652. d = _mergeCategories(d, d3)
  653. if d is None:
  654. continue
  655. new_op = "r" + d + "curveto"
  656. elif d3 == "r":
  657. d0 = _mergeCategories(d0, _negateCategory(d))
  658. if d0 is None:
  659. continue
  660. new_op = d0 + "r" + "curveto"
  661. else:
  662. d0 = _mergeCategories(d0, d3)
  663. if d0 is None:
  664. continue
  665. new_op = d0 + d + "curveto"
  666. # Make sure the stack depth does not exceed (maxstack - 1), so
  667. # that subroutinizer can insert subroutine calls at any point.
  668. if new_op and len(args1) + len(args2) < maxstack:
  669. commands[i - 1] = (new_op, args1 + args2)
  670. del commands[i]
  671. # 6. Resolve any remaining made-up operators into real operators.
  672. for i in range(len(commands)):
  673. op, args = commands[i]
  674. if op in {"0moveto", "0lineto"}:
  675. commands[i] = "h" + op[1:], args
  676. continue
  677. if op[2:] == "curveto" and op[:2] not in {"rr", "hh", "vv", "vh", "hv"}:
  678. op0, op1 = op[:2]
  679. if (op0 == "r") ^ (op1 == "r"):
  680. assert len(args) % 2 == 1
  681. if op0 == "0":
  682. op0 = "h"
  683. if op1 == "0":
  684. op1 = "h"
  685. if op0 == "r":
  686. op0 = op1
  687. if op1 == "r":
  688. op1 = _negateCategory(op0)
  689. assert {op0, op1} <= {"h", "v"}, (op0, op1)
  690. if len(args) % 2:
  691. if op0 != op1: # vhcurveto / hvcurveto
  692. if (op0 == "h") ^ (len(args) % 8 == 1):
  693. # Swap last two args order
  694. args = args[:-2] + args[-1:] + args[-2:-1]
  695. else: # hhcurveto / vvcurveto
  696. if op0 == "h": # hhcurveto
  697. # Swap first two args order
  698. args = args[1:2] + args[:1] + args[2:]
  699. commands[i] = op0 + op1 + "curveto", args
  700. continue
  701. # 7. For any series of args which are blend lists, convert the series to a single blend arg.
  702. for i in range(len(commands)):
  703. op, args = commands[i]
  704. if any(isinstance(arg, list) for arg in args):
  705. commands[i] = op, _convertToBlendCmds(args)
  706. return commands
  707. def specializeProgram(program, getNumRegions=None, **kwargs):
  708. return commandsToProgram(
  709. specializeCommands(programToCommands(program, getNumRegions), **kwargs)
  710. )
  711. if __name__ == "__main__":
  712. import sys
  713. if len(sys.argv) == 1:
  714. import doctest
  715. sys.exit(doctest.testmod().failed)
  716. import argparse
  717. parser = argparse.ArgumentParser(
  718. "fonttools cffLib.specializer",
  719. description="CFF CharString generalizer/specializer",
  720. )
  721. parser.add_argument("program", metavar="command", nargs="*", help="Commands.")
  722. parser.add_argument(
  723. "--num-regions",
  724. metavar="NumRegions",
  725. nargs="*",
  726. default=None,
  727. help="Number of variable-font regions for blend opertaions.",
  728. )
  729. options = parser.parse_args(sys.argv[1:])
  730. getNumRegions = (
  731. None
  732. if options.num_regions is None
  733. else lambda vsIndex: int(options.num_regions[0 if vsIndex is None else vsIndex])
  734. )
  735. program = stringToProgram(options.program)
  736. print("Program:")
  737. print(programToString(program))
  738. commands = programToCommands(program, getNumRegions)
  739. print("Commands:")
  740. print(commands)
  741. program2 = commandsToProgram(commands)
  742. print("Program from commands:")
  743. print(programToString(program2))
  744. assert program == program2
  745. print("Generalized program:")
  746. print(programToString(generalizeProgram(program, getNumRegions)))
  747. print("Specialized program:")
  748. print(programToString(specializeProgram(program, getNumRegions)))