pointPen.py 22 KB

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