recordingPen.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. """Pen recording operations that can be accessed or replayed."""
  2. from fontTools.pens.basePen import AbstractPen, DecomposingPen
  3. from fontTools.pens.pointPen import AbstractPointPen, DecomposingPointPen
  4. __all__ = [
  5. "replayRecording",
  6. "RecordingPen",
  7. "DecomposingRecordingPen",
  8. "DecomposingRecordingPointPen",
  9. "RecordingPointPen",
  10. "lerpRecordings",
  11. ]
  12. def replayRecording(recording, pen):
  13. """Replay a recording, as produced by RecordingPen or DecomposingRecordingPen,
  14. to a pen.
  15. Note that recording does not have to be produced by those pens.
  16. It can be any iterable of tuples of method name and tuple-of-arguments.
  17. Likewise, pen can be any objects receiving those method calls.
  18. """
  19. for operator, operands in recording:
  20. getattr(pen, operator)(*operands)
  21. class RecordingPen(AbstractPen):
  22. """Pen recording operations that can be accessed or replayed.
  23. The recording can be accessed as pen.value; or replayed using
  24. pen.replay(otherPen).
  25. :Example:
  26. from fontTools.ttLib import TTFont
  27. from fontTools.pens.recordingPen import RecordingPen
  28. glyph_name = 'dollar'
  29. font_path = 'MyFont.otf'
  30. font = TTFont(font_path)
  31. glyphset = font.getGlyphSet()
  32. glyph = glyphset[glyph_name]
  33. pen = RecordingPen()
  34. glyph.draw(pen)
  35. print(pen.value)
  36. """
  37. def __init__(self):
  38. self.value = []
  39. def moveTo(self, p0):
  40. self.value.append(("moveTo", (p0,)))
  41. def lineTo(self, p1):
  42. self.value.append(("lineTo", (p1,)))
  43. def qCurveTo(self, *points):
  44. self.value.append(("qCurveTo", points))
  45. def curveTo(self, *points):
  46. self.value.append(("curveTo", points))
  47. def closePath(self):
  48. self.value.append(("closePath", ()))
  49. def endPath(self):
  50. self.value.append(("endPath", ()))
  51. def addComponent(self, glyphName, transformation):
  52. self.value.append(("addComponent", (glyphName, transformation)))
  53. def addVarComponent(self, glyphName, transformation, location):
  54. self.value.append(("addVarComponent", (glyphName, transformation, location)))
  55. def replay(self, pen):
  56. replayRecording(self.value, pen)
  57. draw = replay
  58. class DecomposingRecordingPen(DecomposingPen, RecordingPen):
  59. """Same as RecordingPen, except that it doesn't keep components
  60. as references, but draws them decomposed as regular contours.
  61. The constructor takes a required 'glyphSet' positional argument,
  62. a dictionary of glyph objects (i.e. with a 'draw' method) keyed
  63. by thir name; other arguments are forwarded to the DecomposingPen's
  64. constructor::
  65. >>> class SimpleGlyph(object):
  66. ... def draw(self, pen):
  67. ... pen.moveTo((0, 0))
  68. ... pen.curveTo((1, 1), (2, 2), (3, 3))
  69. ... pen.closePath()
  70. >>> class CompositeGlyph(object):
  71. ... def draw(self, pen):
  72. ... pen.addComponent('a', (1, 0, 0, 1, -1, 1))
  73. >>> class MissingComponent(object):
  74. ... def draw(self, pen):
  75. ... pen.addComponent('foobar', (1, 0, 0, 1, 0, 0))
  76. >>> class FlippedComponent(object):
  77. ... def draw(self, pen):
  78. ... pen.addComponent('a', (-1, 0, 0, 1, 0, 0))
  79. >>> glyphSet = {
  80. ... 'a': SimpleGlyph(),
  81. ... 'b': CompositeGlyph(),
  82. ... 'c': MissingComponent(),
  83. ... 'd': FlippedComponent(),
  84. ... }
  85. >>> for name, glyph in sorted(glyphSet.items()):
  86. ... pen = DecomposingRecordingPen(glyphSet)
  87. ... try:
  88. ... glyph.draw(pen)
  89. ... except pen.MissingComponentError:
  90. ... pass
  91. ... print("{}: {}".format(name, pen.value))
  92. a: [('moveTo', ((0, 0),)), ('curveTo', ((1, 1), (2, 2), (3, 3))), ('closePath', ())]
  93. b: [('moveTo', ((-1, 1),)), ('curveTo', ((0, 2), (1, 3), (2, 4))), ('closePath', ())]
  94. c: []
  95. d: [('moveTo', ((0, 0),)), ('curveTo', ((-1, 1), (-2, 2), (-3, 3))), ('closePath', ())]
  96. >>> for name, glyph in sorted(glyphSet.items()):
  97. ... pen = DecomposingRecordingPen(
  98. ... glyphSet, skipMissingComponents=True, reverseFlipped=True,
  99. ... )
  100. ... glyph.draw(pen)
  101. ... print("{}: {}".format(name, pen.value))
  102. a: [('moveTo', ((0, 0),)), ('curveTo', ((1, 1), (2, 2), (3, 3))), ('closePath', ())]
  103. b: [('moveTo', ((-1, 1),)), ('curveTo', ((0, 2), (1, 3), (2, 4))), ('closePath', ())]
  104. c: []
  105. d: [('moveTo', ((0, 0),)), ('lineTo', ((-3, 3),)), ('curveTo', ((-2, 2), (-1, 1), (0, 0))), ('closePath', ())]
  106. """
  107. # raises MissingComponentError(KeyError) if base glyph is not found in glyphSet
  108. skipMissingComponents = False
  109. class RecordingPointPen(AbstractPointPen):
  110. """PointPen recording operations that can be accessed or replayed.
  111. The recording can be accessed as pen.value; or replayed using
  112. pointPen.replay(otherPointPen).
  113. :Example:
  114. from defcon import Font
  115. from fontTools.pens.recordingPen import RecordingPointPen
  116. glyph_name = 'a'
  117. font_path = 'MyFont.ufo'
  118. font = Font(font_path)
  119. glyph = font[glyph_name]
  120. pen = RecordingPointPen()
  121. glyph.drawPoints(pen)
  122. print(pen.value)
  123. new_glyph = font.newGlyph('b')
  124. pen.replay(new_glyph.getPointPen())
  125. """
  126. def __init__(self):
  127. self.value = []
  128. def beginPath(self, identifier=None, **kwargs):
  129. if identifier is not None:
  130. kwargs["identifier"] = identifier
  131. self.value.append(("beginPath", (), kwargs))
  132. def endPath(self):
  133. self.value.append(("endPath", (), {}))
  134. def addPoint(
  135. self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
  136. ):
  137. if identifier is not None:
  138. kwargs["identifier"] = identifier
  139. self.value.append(("addPoint", (pt, segmentType, smooth, name), kwargs))
  140. def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
  141. if identifier is not None:
  142. kwargs["identifier"] = identifier
  143. self.value.append(("addComponent", (baseGlyphName, transformation), kwargs))
  144. def addVarComponent(
  145. self, baseGlyphName, transformation, location, identifier=None, **kwargs
  146. ):
  147. if identifier is not None:
  148. kwargs["identifier"] = identifier
  149. self.value.append(
  150. ("addVarComponent", (baseGlyphName, transformation, location), kwargs)
  151. )
  152. def replay(self, pointPen):
  153. for operator, args, kwargs in self.value:
  154. getattr(pointPen, operator)(*args, **kwargs)
  155. drawPoints = replay
  156. class DecomposingRecordingPointPen(DecomposingPointPen, RecordingPointPen):
  157. """Same as RecordingPointPen, except that it doesn't keep components
  158. as references, but draws them decomposed as regular contours.
  159. The constructor takes a required 'glyphSet' positional argument,
  160. a dictionary of pointPen-drawable glyph objects (i.e. with a 'drawPoints' method)
  161. keyed by thir name; other arguments are forwarded to the DecomposingPointPen's
  162. constructor::
  163. >>> from pprint import pprint
  164. >>> class SimpleGlyph(object):
  165. ... def drawPoints(self, pen):
  166. ... pen.beginPath()
  167. ... pen.addPoint((0, 0), "line")
  168. ... pen.addPoint((1, 1))
  169. ... pen.addPoint((2, 2))
  170. ... pen.addPoint((3, 3), "curve")
  171. ... pen.endPath()
  172. >>> class CompositeGlyph(object):
  173. ... def drawPoints(self, pen):
  174. ... pen.addComponent('a', (1, 0, 0, 1, -1, 1))
  175. >>> class MissingComponent(object):
  176. ... def drawPoints(self, pen):
  177. ... pen.addComponent('foobar', (1, 0, 0, 1, 0, 0))
  178. >>> class FlippedComponent(object):
  179. ... def drawPoints(self, pen):
  180. ... pen.addComponent('a', (-1, 0, 0, 1, 0, 0))
  181. >>> glyphSet = {
  182. ... 'a': SimpleGlyph(),
  183. ... 'b': CompositeGlyph(),
  184. ... 'c': MissingComponent(),
  185. ... 'd': FlippedComponent(),
  186. ... }
  187. >>> for name, glyph in sorted(glyphSet.items()):
  188. ... pen = DecomposingRecordingPointPen(glyphSet)
  189. ... try:
  190. ... glyph.drawPoints(pen)
  191. ... except pen.MissingComponentError:
  192. ... pass
  193. ... pprint({name: pen.value})
  194. {'a': [('beginPath', (), {}),
  195. ('addPoint', ((0, 0), 'line', False, None), {}),
  196. ('addPoint', ((1, 1), None, False, None), {}),
  197. ('addPoint', ((2, 2), None, False, None), {}),
  198. ('addPoint', ((3, 3), 'curve', False, None), {}),
  199. ('endPath', (), {})]}
  200. {'b': [('beginPath', (), {}),
  201. ('addPoint', ((-1, 1), 'line', False, None), {}),
  202. ('addPoint', ((0, 2), None, False, None), {}),
  203. ('addPoint', ((1, 3), None, False, None), {}),
  204. ('addPoint', ((2, 4), 'curve', False, None), {}),
  205. ('endPath', (), {})]}
  206. {'c': []}
  207. {'d': [('beginPath', (), {}),
  208. ('addPoint', ((0, 0), 'line', False, None), {}),
  209. ('addPoint', ((-1, 1), None, False, None), {}),
  210. ('addPoint', ((-2, 2), None, False, None), {}),
  211. ('addPoint', ((-3, 3), 'curve', False, None), {}),
  212. ('endPath', (), {})]}
  213. >>> for name, glyph in sorted(glyphSet.items()):
  214. ... pen = DecomposingRecordingPointPen(
  215. ... glyphSet, skipMissingComponents=True, reverseFlipped=True,
  216. ... )
  217. ... glyph.drawPoints(pen)
  218. ... pprint({name: pen.value})
  219. {'a': [('beginPath', (), {}),
  220. ('addPoint', ((0, 0), 'line', False, None), {}),
  221. ('addPoint', ((1, 1), None, False, None), {}),
  222. ('addPoint', ((2, 2), None, False, None), {}),
  223. ('addPoint', ((3, 3), 'curve', False, None), {}),
  224. ('endPath', (), {})]}
  225. {'b': [('beginPath', (), {}),
  226. ('addPoint', ((-1, 1), 'line', False, None), {}),
  227. ('addPoint', ((0, 2), None, False, None), {}),
  228. ('addPoint', ((1, 3), None, False, None), {}),
  229. ('addPoint', ((2, 4), 'curve', False, None), {}),
  230. ('endPath', (), {})]}
  231. {'c': []}
  232. {'d': [('beginPath', (), {}),
  233. ('addPoint', ((0, 0), 'curve', False, None), {}),
  234. ('addPoint', ((-3, 3), 'line', False, None), {}),
  235. ('addPoint', ((-2, 2), None, False, None), {}),
  236. ('addPoint', ((-1, 1), None, False, None), {}),
  237. ('endPath', (), {})]}
  238. """
  239. # raises MissingComponentError(KeyError) if base glyph is not found in glyphSet
  240. skipMissingComponents = False
  241. def lerpRecordings(recording1, recording2, factor=0.5):
  242. """Linearly interpolate between two recordings. The recordings
  243. must be decomposed, i.e. they must not contain any components.
  244. Factor is typically between 0 and 1. 0 means the first recording,
  245. 1 means the second recording, and 0.5 means the average of the
  246. two recordings. Other values are possible, and can be useful to
  247. extrapolate. Defaults to 0.5.
  248. Returns a generator with the new recording.
  249. """
  250. if len(recording1) != len(recording2):
  251. raise ValueError(
  252. "Mismatched lengths: %d and %d" % (len(recording1), len(recording2))
  253. )
  254. for (op1, args1), (op2, args2) in zip(recording1, recording2):
  255. if op1 != op2:
  256. raise ValueError("Mismatched operations: %s, %s" % (op1, op2))
  257. if op1 == "addComponent":
  258. raise ValueError("Cannot interpolate components")
  259. else:
  260. mid_args = [
  261. (x1 + (x2 - x1) * factor, y1 + (y2 - y1) * factor)
  262. for (x1, y1), (x2, y2) in zip(args1, args2)
  263. ]
  264. yield (op1, mid_args)
  265. if __name__ == "__main__":
  266. pen = RecordingPen()
  267. pen.moveTo((0, 0))
  268. pen.lineTo((0, 100))
  269. pen.curveTo((50, 75), (60, 50), (50, 25))
  270. pen.closePath()
  271. from pprint import pprint
  272. pprint(pen.value)