pointPen.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  1. """
  2. =========
  3. PointPens
  4. =========
  5. Where **SegmentPens** have an intuitive approach to drawing
  6. (if you're familiar with postscript anyway), the **PointPen**
  7. is geared towards accessing all the data in the contours of
  8. the glyph. A PointPen has a very simple interface, it just
  9. steps through all the points in a call from glyph.drawPoints().
  10. This allows the caller to provide more data for each point.
  11. For instance, whether or not a point is smooth, and its name.
  12. """
  13. import math
  14. from typing import Any, Optional, Tuple, Dict
  15. from fontTools.pens.basePen import AbstractPen, PenError
  16. from fontTools.misc.transform import DecomposedTransform
  17. __all__ = [
  18. "AbstractPointPen",
  19. "BasePointToSegmentPen",
  20. "PointToSegmentPen",
  21. "SegmentToPointPen",
  22. "GuessSmoothPointPen",
  23. "ReverseContourPointPen",
  24. ]
  25. class AbstractPointPen:
  26. """Baseclass for all PointPens."""
  27. def beginPath(self, identifier: Optional[str] = None, **kwargs: Any) -> None:
  28. """Start a new sub path."""
  29. raise NotImplementedError
  30. def endPath(self) -> None:
  31. """End the current sub path."""
  32. raise NotImplementedError
  33. def addPoint(
  34. self,
  35. pt: Tuple[float, float],
  36. segmentType: Optional[str] = None,
  37. smooth: bool = False,
  38. name: Optional[str] = None,
  39. identifier: Optional[str] = None,
  40. **kwargs: Any,
  41. ) -> None:
  42. """Add a point to the current sub path."""
  43. raise NotImplementedError
  44. def addComponent(
  45. self,
  46. baseGlyphName: str,
  47. transformation: Tuple[float, float, float, float, float, float],
  48. identifier: Optional[str] = None,
  49. **kwargs: Any,
  50. ) -> None:
  51. """Add a sub glyph."""
  52. raise NotImplementedError
  53. def addVarComponent(
  54. self,
  55. glyphName: str,
  56. transformation: DecomposedTransform,
  57. location: Dict[str, float],
  58. identifier: Optional[str] = None,
  59. **kwargs: Any,
  60. ) -> None:
  61. """Add a VarComponent sub glyph. The 'transformation' argument
  62. must be a DecomposedTransform from the fontTools.misc.transform module,
  63. and the 'location' argument must be a dictionary mapping axis tags
  64. to their locations.
  65. """
  66. # ttGlyphSet decomposes for us
  67. raise AttributeError
  68. class BasePointToSegmentPen(AbstractPointPen):
  69. """
  70. Base class for retrieving the outline in a segment-oriented
  71. way. The PointPen protocol is simple yet also a little tricky,
  72. so when you need an outline presented as segments but you have
  73. as points, do use this base implementation as it properly takes
  74. care of all the edge cases.
  75. """
  76. def __init__(self):
  77. self.currentPath = None
  78. def beginPath(self, identifier=None, **kwargs):
  79. if self.currentPath is not None:
  80. raise PenError("Path already begun.")
  81. self.currentPath = []
  82. def _flushContour(self, segments):
  83. """Override this method.
  84. It will be called for each non-empty sub path with a list
  85. of segments: the 'segments' argument.
  86. The segments list contains tuples of length 2:
  87. (segmentType, points)
  88. segmentType is one of "move", "line", "curve" or "qcurve".
  89. "move" may only occur as the first segment, and it signifies
  90. an OPEN path. A CLOSED path does NOT start with a "move", in
  91. fact it will not contain a "move" at ALL.
  92. The 'points' field in the 2-tuple is a list of point info
  93. tuples. The list has 1 or more items, a point tuple has
  94. four items:
  95. (point, smooth, name, kwargs)
  96. 'point' is an (x, y) coordinate pair.
  97. For a closed path, the initial moveTo point is defined as
  98. the last point of the last segment.
  99. The 'points' list of "move" and "line" segments always contains
  100. exactly one point tuple.
  101. """
  102. raise NotImplementedError
  103. def endPath(self):
  104. if self.currentPath is None:
  105. raise PenError("Path not begun.")
  106. points = self.currentPath
  107. self.currentPath = None
  108. if not points:
  109. return
  110. if len(points) == 1:
  111. # Not much more we can do than output a single move segment.
  112. pt, segmentType, smooth, name, kwargs = points[0]
  113. segments = [("move", [(pt, smooth, name, kwargs)])]
  114. self._flushContour(segments)
  115. return
  116. segments = []
  117. if points[0][1] == "move":
  118. # It's an open contour, insert a "move" segment for the first
  119. # point and remove that first point from the point list.
  120. pt, segmentType, smooth, name, kwargs = points[0]
  121. segments.append(("move", [(pt, smooth, name, kwargs)]))
  122. points.pop(0)
  123. else:
  124. # It's a closed contour. Locate the first on-curve point, and
  125. # rotate the point list so that it _ends_ with an on-curve
  126. # point.
  127. firstOnCurve = None
  128. for i in range(len(points)):
  129. segmentType = points[i][1]
  130. if segmentType is not None:
  131. firstOnCurve = i
  132. break
  133. if firstOnCurve is None:
  134. # Special case for quadratics: a contour with no on-curve
  135. # points. Add a "None" point. (See also the Pen protocol's
  136. # qCurveTo() method and fontTools.pens.basePen.py.)
  137. points.append((None, "qcurve", None, None, None))
  138. else:
  139. points = points[firstOnCurve + 1 :] + points[: firstOnCurve + 1]
  140. currentSegment = []
  141. for pt, segmentType, smooth, name, kwargs in points:
  142. currentSegment.append((pt, smooth, name, kwargs))
  143. if segmentType is None:
  144. continue
  145. segments.append((segmentType, currentSegment))
  146. currentSegment = []
  147. self._flushContour(segments)
  148. def addPoint(
  149. self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
  150. ):
  151. if self.currentPath is None:
  152. raise PenError("Path not begun")
  153. self.currentPath.append((pt, segmentType, smooth, name, kwargs))
  154. class PointToSegmentPen(BasePointToSegmentPen):
  155. """
  156. Adapter class that converts the PointPen protocol to the
  157. (Segment)Pen protocol.
  158. NOTE: The segment pen does not support and will drop point names, identifiers
  159. and kwargs.
  160. """
  161. def __init__(self, segmentPen, outputImpliedClosingLine=False):
  162. BasePointToSegmentPen.__init__(self)
  163. self.pen = segmentPen
  164. self.outputImpliedClosingLine = outputImpliedClosingLine
  165. def _flushContour(self, segments):
  166. if not segments:
  167. raise PenError("Must have at least one segment.")
  168. pen = self.pen
  169. if segments[0][0] == "move":
  170. # It's an open path.
  171. closed = False
  172. points = segments[0][1]
  173. if len(points) != 1:
  174. raise PenError(f"Illegal move segment point count: {len(points)}")
  175. movePt, _, _, _ = points[0]
  176. del segments[0]
  177. else:
  178. # It's a closed path, do a moveTo to the last
  179. # point of the last segment.
  180. closed = True
  181. segmentType, points = segments[-1]
  182. movePt, _, _, _ = points[-1]
  183. if movePt is None:
  184. # quad special case: a contour with no on-curve points contains
  185. # one "qcurve" segment that ends with a point that's None. We
  186. # must not output a moveTo() in that case.
  187. pass
  188. else:
  189. pen.moveTo(movePt)
  190. outputImpliedClosingLine = self.outputImpliedClosingLine
  191. nSegments = len(segments)
  192. lastPt = movePt
  193. for i in range(nSegments):
  194. segmentType, points = segments[i]
  195. points = [pt for pt, _, _, _ in points]
  196. if segmentType == "line":
  197. if len(points) != 1:
  198. raise PenError(f"Illegal line segment point count: {len(points)}")
  199. pt = points[0]
  200. # For closed contours, a 'lineTo' is always implied from the last oncurve
  201. # point to the starting point, thus we can omit it when the last and
  202. # starting point don't overlap.
  203. # However, when the last oncurve point is a "line" segment and has same
  204. # coordinates as the starting point of a closed contour, we need to output
  205. # the closing 'lineTo' explicitly (regardless of the value of the
  206. # 'outputImpliedClosingLine' option) in order to disambiguate this case from
  207. # the implied closing 'lineTo', otherwise the duplicate point would be lost.
  208. # See https://github.com/googlefonts/fontmake/issues/572.
  209. if (
  210. i + 1 != nSegments
  211. or outputImpliedClosingLine
  212. or not closed
  213. or pt == lastPt
  214. ):
  215. pen.lineTo(pt)
  216. lastPt = pt
  217. elif segmentType == "curve":
  218. pen.curveTo(*points)
  219. lastPt = points[-1]
  220. elif segmentType == "qcurve":
  221. pen.qCurveTo(*points)
  222. lastPt = points[-1]
  223. else:
  224. raise PenError(f"Illegal segmentType: {segmentType}")
  225. if closed:
  226. pen.closePath()
  227. else:
  228. pen.endPath()
  229. def addComponent(self, glyphName, transform, identifier=None, **kwargs):
  230. del identifier # unused
  231. del kwargs # unused
  232. self.pen.addComponent(glyphName, transform)
  233. class SegmentToPointPen(AbstractPen):
  234. """
  235. Adapter class that converts the (Segment)Pen protocol to the
  236. PointPen protocol.
  237. """
  238. def __init__(self, pointPen, guessSmooth=True):
  239. if guessSmooth:
  240. self.pen = GuessSmoothPointPen(pointPen)
  241. else:
  242. self.pen = pointPen
  243. self.contour = None
  244. def _flushContour(self):
  245. pen = self.pen
  246. pen.beginPath()
  247. for pt, segmentType in self.contour:
  248. pen.addPoint(pt, segmentType=segmentType)
  249. pen.endPath()
  250. def moveTo(self, pt):
  251. self.contour = []
  252. self.contour.append((pt, "move"))
  253. def lineTo(self, pt):
  254. if self.contour is None:
  255. raise PenError("Contour missing required initial moveTo")
  256. self.contour.append((pt, "line"))
  257. def curveTo(self, *pts):
  258. if not pts:
  259. raise TypeError("Must pass in at least one point")
  260. if self.contour is None:
  261. raise PenError("Contour missing required initial moveTo")
  262. for pt in pts[:-1]:
  263. self.contour.append((pt, None))
  264. self.contour.append((pts[-1], "curve"))
  265. def qCurveTo(self, *pts):
  266. if not pts:
  267. raise TypeError("Must pass in at least one point")
  268. if pts[-1] is None:
  269. self.contour = []
  270. else:
  271. if self.contour is None:
  272. raise PenError("Contour missing required initial moveTo")
  273. for pt in pts[:-1]:
  274. self.contour.append((pt, None))
  275. if pts[-1] is not None:
  276. self.contour.append((pts[-1], "qcurve"))
  277. def closePath(self):
  278. if self.contour is None:
  279. raise PenError("Contour missing required initial moveTo")
  280. if len(self.contour) > 1 and self.contour[0][0] == self.contour[-1][0]:
  281. self.contour[0] = self.contour[-1]
  282. del self.contour[-1]
  283. else:
  284. # There's an implied line at the end, replace "move" with "line"
  285. # for the first point
  286. pt, tp = self.contour[0]
  287. if tp == "move":
  288. self.contour[0] = pt, "line"
  289. self._flushContour()
  290. self.contour = None
  291. def endPath(self):
  292. if self.contour is None:
  293. raise PenError("Contour missing required initial moveTo")
  294. self._flushContour()
  295. self.contour = None
  296. def addComponent(self, glyphName, transform):
  297. if self.contour is not None:
  298. raise PenError("Components must be added before or after contours")
  299. self.pen.addComponent(glyphName, transform)
  300. class GuessSmoothPointPen(AbstractPointPen):
  301. """
  302. Filtering PointPen that tries to determine whether an on-curve point
  303. should be "smooth", ie. that it's a "tangent" point or a "curve" point.
  304. """
  305. def __init__(self, outPen, error=0.05):
  306. self._outPen = outPen
  307. self._error = error
  308. self._points = None
  309. def _flushContour(self):
  310. if self._points is None:
  311. raise PenError("Path not begun")
  312. points = self._points
  313. nPoints = len(points)
  314. if not nPoints:
  315. return
  316. if points[0][1] == "move":
  317. # Open path.
  318. indices = range(1, nPoints - 1)
  319. elif nPoints > 1:
  320. # Closed path. To avoid having to mod the contour index, we
  321. # simply abuse Python's negative index feature, and start at -1
  322. indices = range(-1, nPoints - 1)
  323. else:
  324. # closed path containing 1 point (!), ignore.
  325. indices = []
  326. for i in indices:
  327. pt, segmentType, _, name, kwargs = points[i]
  328. if segmentType is None:
  329. continue
  330. prev = i - 1
  331. next = i + 1
  332. if points[prev][1] is not None and points[next][1] is not None:
  333. continue
  334. # At least one of our neighbors is an off-curve point
  335. pt = points[i][0]
  336. prevPt = points[prev][0]
  337. nextPt = points[next][0]
  338. if pt != prevPt and pt != nextPt:
  339. dx1, dy1 = pt[0] - prevPt[0], pt[1] - prevPt[1]
  340. dx2, dy2 = nextPt[0] - pt[0], nextPt[1] - pt[1]
  341. a1 = math.atan2(dy1, dx1)
  342. a2 = math.atan2(dy2, dx2)
  343. if abs(a1 - a2) < self._error:
  344. points[i] = pt, segmentType, True, name, kwargs
  345. for pt, segmentType, smooth, name, kwargs in points:
  346. self._outPen.addPoint(pt, segmentType, smooth, name, **kwargs)
  347. def beginPath(self, identifier=None, **kwargs):
  348. if self._points is not None:
  349. raise PenError("Path already begun")
  350. self._points = []
  351. if identifier is not None:
  352. kwargs["identifier"] = identifier
  353. self._outPen.beginPath(**kwargs)
  354. def endPath(self):
  355. self._flushContour()
  356. self._outPen.endPath()
  357. self._points = None
  358. def addPoint(
  359. self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
  360. ):
  361. if self._points is None:
  362. raise PenError("Path not begun")
  363. if identifier is not None:
  364. kwargs["identifier"] = identifier
  365. self._points.append((pt, segmentType, False, name, kwargs))
  366. def addComponent(self, glyphName, transformation, identifier=None, **kwargs):
  367. if self._points is not None:
  368. raise PenError("Components must be added before or after contours")
  369. if identifier is not None:
  370. kwargs["identifier"] = identifier
  371. self._outPen.addComponent(glyphName, transformation, **kwargs)
  372. def addVarComponent(
  373. self, glyphName, transformation, location, identifier=None, **kwargs
  374. ):
  375. if self._points is not None:
  376. raise PenError("VarComponents must be added before or after contours")
  377. if identifier is not None:
  378. kwargs["identifier"] = identifier
  379. self._outPen.addVarComponent(glyphName, transformation, location, **kwargs)
  380. class ReverseContourPointPen(AbstractPointPen):
  381. """
  382. This is a PointPen that passes outline data to another PointPen, but
  383. reversing the winding direction of all contours. Components are simply
  384. passed through unchanged.
  385. Closed contours are reversed in such a way that the first point remains
  386. the first point.
  387. """
  388. def __init__(self, outputPointPen):
  389. self.pen = outputPointPen
  390. # a place to store the points for the current sub path
  391. self.currentContour = None
  392. def _flushContour(self):
  393. pen = self.pen
  394. contour = self.currentContour
  395. if not contour:
  396. pen.beginPath(identifier=self.currentContourIdentifier)
  397. pen.endPath()
  398. return
  399. closed = contour[0][1] != "move"
  400. if not closed:
  401. lastSegmentType = "move"
  402. else:
  403. # Remove the first point and insert it at the end. When
  404. # the list of points gets reversed, this point will then
  405. # again be at the start. In other words, the following
  406. # will hold:
  407. # for N in range(len(originalContour)):
  408. # originalContour[N] == reversedContour[-N]
  409. contour.append(contour.pop(0))
  410. # Find the first on-curve point.
  411. firstOnCurve = None
  412. for i in range(len(contour)):
  413. if contour[i][1] is not None:
  414. firstOnCurve = i
  415. break
  416. if firstOnCurve is None:
  417. # There are no on-curve points, be basically have to
  418. # do nothing but contour.reverse().
  419. lastSegmentType = None
  420. else:
  421. lastSegmentType = contour[firstOnCurve][1]
  422. contour.reverse()
  423. if not closed:
  424. # Open paths must start with a move, so we simply dump
  425. # all off-curve points leading up to the first on-curve.
  426. while contour[0][1] is None:
  427. contour.pop(0)
  428. pen.beginPath(identifier=self.currentContourIdentifier)
  429. for pt, nextSegmentType, smooth, name, kwargs in contour:
  430. if nextSegmentType is not None:
  431. segmentType = lastSegmentType
  432. lastSegmentType = nextSegmentType
  433. else:
  434. segmentType = None
  435. pen.addPoint(
  436. pt, segmentType=segmentType, smooth=smooth, name=name, **kwargs
  437. )
  438. pen.endPath()
  439. def beginPath(self, identifier=None, **kwargs):
  440. if self.currentContour is not None:
  441. raise PenError("Path already begun")
  442. self.currentContour = []
  443. self.currentContourIdentifier = identifier
  444. self.onCurve = []
  445. def endPath(self):
  446. if self.currentContour is None:
  447. raise PenError("Path not begun")
  448. self._flushContour()
  449. self.currentContour = None
  450. def addPoint(
  451. self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs
  452. ):
  453. if self.currentContour is None:
  454. raise PenError("Path not begun")
  455. if identifier is not None:
  456. kwargs["identifier"] = identifier
  457. self.currentContour.append((pt, segmentType, smooth, name, kwargs))
  458. def addComponent(self, glyphName, transform, identifier=None, **kwargs):
  459. if self.currentContour is not None:
  460. raise PenError("Components must be added before or after contours")
  461. self.pen.addComponent(glyphName, transform, identifier=identifier, **kwargs)