specializer.py 30 KB

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