content
stringlengths
1
103k
path
stringlengths
8
216
filename
stringlengths
2
179
language
stringclasses
15 values
size_bytes
int64
2
189k
quality_score
float64
0.5
0.95
complexity
float64
0
1
documentation_ratio
float64
0
1
repository
stringclasses
5 values
stars
int64
0
1k
created_date
stringdate
2023-07-10 19:21:08
2025-07-09 19:11:45
license
stringclasses
4 values
is_test
bool
2 classes
file_hash
stringlengths
32
32
\n\n
.venv\Lib\site-packages\fontTools\otlLib\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
244
0.85
0
0
vue-tools
142
2024-06-22T19:53:42.995296
MIT
false
52c7a080f876cac2cb2b04793cce3b58
"""Calculate the area of a glyph."""\n\nfrom fontTools.pens.basePen import BasePen\n\n\n__all__ = ["AreaPen"]\n\n\nclass AreaPen(BasePen):\n def __init__(self, glyphset=None):\n BasePen.__init__(self, glyphset)\n self.value = 0\n\n def _moveTo(self, p0):\n self._p0 = self._startPoint = p0\n\n def _lineTo(self, p1):\n x0, y0 = self._p0\n x1, y1 = p1\n self.value -= (x1 - x0) * (y1 + y0) * 0.5\n self._p0 = p1\n\n def _qCurveToOne(self, p1, p2):\n # https://github.com/Pomax/bezierinfo/issues/44\n p0 = self._p0\n x0, y0 = p0[0], p0[1]\n x1, y1 = p1[0] - x0, p1[1] - y0\n x2, y2 = p2[0] - x0, p2[1] - y0\n self.value -= (x2 * y1 - x1 * y2) / 3\n self._lineTo(p2)\n self._p0 = p2\n\n def _curveToOne(self, p1, p2, p3):\n # https://github.com/Pomax/bezierinfo/issues/44\n p0 = self._p0\n x0, y0 = p0[0], p0[1]\n x1, y1 = p1[0] - x0, p1[1] - y0\n x2, y2 = p2[0] - x0, p2[1] - y0\n x3, y3 = p3[0] - x0, p3[1] - y0\n self.value -= (x1 * (-y2 - y3) + x2 * (y1 - 2 * y3) + x3 * (y1 + 2 * y2)) * 0.15\n self._lineTo(p3)\n self._p0 = p3\n\n def _closePath(self):\n self._lineTo(self._startPoint)\n del self._p0, self._startPoint\n\n def _endPath(self):\n if self._p0 != self._startPoint:\n # Area is not defined for open contours.\n raise NotImplementedError\n del self._p0, self._startPoint\n
.venv\Lib\site-packages\fontTools\pens\areaPen.py
areaPen.py
Python
1,524
0.95
0.192308
0.073171
python-kit
184
2025-04-25T07:57:17.221357
BSD-3-Clause
false
cf7c2488f9a70710641b0bdff7cec4b6
"""fontTools.pens.basePen.py -- Tools and base classes to build pen objects.\n\nThe Pen Protocol\n\nA Pen is a kind of object that standardizes the way how to "draw" outlines:\nit is a middle man between an outline and a drawing. In other words:\nit is an abstraction for drawing outlines, making sure that outline objects\ndon't need to know the details about how and where they're being drawn, and\nthat drawings don't need to know the details of how outlines are stored.\n\nThe most basic pattern is this::\n\n outline.draw(pen) # 'outline' draws itself onto 'pen'\n\nPens can be used to render outlines to the screen, but also to construct\nnew outlines. Eg. an outline object can be both a drawable object (it has a\ndraw() method) as well as a pen itself: you *build* an outline using pen\nmethods.\n\nThe AbstractPen class defines the Pen protocol. It implements almost\nnothing (only no-op closePath() and endPath() methods), but is useful\nfor documentation purposes. Subclassing it basically tells the reader:\n"this class implements the Pen protocol.". An examples of an AbstractPen\nsubclass is :py:class:`fontTools.pens.transformPen.TransformPen`.\n\nThe BasePen class is a base implementation useful for pens that actually\ndraw (for example a pen renders outlines using a native graphics engine).\nBasePen contains a lot of base functionality, making it very easy to build\na pen that fully conforms to the pen protocol. Note that if you subclass\nBasePen, you *don't* override moveTo(), lineTo(), etc., but _moveTo(),\n_lineTo(), etc. See the BasePen doc string for details. Examples of\nBasePen subclasses are fontTools.pens.boundsPen.BoundsPen and\nfontTools.pens.cocoaPen.CocoaPen.\n\nCoordinates are usually expressed as (x, y) tuples, but generally any\nsequence of length 2 will do.\n"""\n\nfrom typing import Tuple, Dict\n\nfrom fontTools.misc.loggingTools import LogMixin\nfrom fontTools.misc.transform import DecomposedTransform, Identity\n\n__all__ = [\n "AbstractPen",\n "NullPen",\n "BasePen",\n "PenError",\n "decomposeSuperBezierSegment",\n "decomposeQuadraticSegment",\n]\n\n\nclass PenError(Exception):\n """Represents an error during penning."""\n\n\nclass OpenContourError(PenError):\n pass\n\n\nclass AbstractPen:\n def moveTo(self, pt: Tuple[float, float]) -> None:\n """Begin a new sub path, set the current point to 'pt'. You must\n end each sub path with a call to pen.closePath() or pen.endPath().\n """\n raise NotImplementedError\n\n def lineTo(self, pt: Tuple[float, float]) -> None:\n """Draw a straight line from the current point to 'pt'."""\n raise NotImplementedError\n\n def curveTo(self, *points: Tuple[float, float]) -> None:\n """Draw a cubic bezier with an arbitrary number of control points.\n\n The last point specified is on-curve, all others are off-curve\n (control) points. If the number of control points is > 2, the\n segment is split into multiple bezier segments. This works\n like this:\n\n Let n be the number of control points (which is the number of\n arguments to this call minus 1). If n==2, a plain vanilla cubic\n bezier is drawn. If n==1, we fall back to a quadratic segment and\n if n==0 we draw a straight line. It gets interesting when n>2:\n n-1 PostScript-style cubic segments will be drawn as if it were\n one curve. See decomposeSuperBezierSegment().\n\n The conversion algorithm used for n>2 is inspired by NURB\n splines, and is conceptually equivalent to the TrueType "implied\n points" principle. See also decomposeQuadraticSegment().\n """\n raise NotImplementedError\n\n def qCurveTo(self, *points: Tuple[float, float]) -> None:\n """Draw a whole string of quadratic curve segments.\n\n The last point specified is on-curve, all others are off-curve\n points.\n\n This method implements TrueType-style curves, breaking up curves\n using 'implied points': between each two consequtive off-curve points,\n there is one implied point exactly in the middle between them. See\n also decomposeQuadraticSegment().\n\n The last argument (normally the on-curve point) may be None.\n This is to support contours that have NO on-curve points (a rarely\n seen feature of TrueType outlines).\n """\n raise NotImplementedError\n\n def closePath(self) -> None:\n """Close the current sub path. You must call either pen.closePath()\n or pen.endPath() after each sub path.\n """\n pass\n\n def endPath(self) -> None:\n """End the current sub path, but don't close it. You must call\n either pen.closePath() or pen.endPath() after each sub path.\n """\n pass\n\n def addComponent(\n self,\n glyphName: str,\n transformation: Tuple[float, float, float, float, float, float],\n ) -> None:\n """Add a sub glyph. The 'transformation' argument must be a 6-tuple\n containing an affine transformation, or a Transform object from the\n fontTools.misc.transform module. More precisely: it should be a\n sequence containing 6 numbers.\n """\n raise NotImplementedError\n\n def addVarComponent(\n self,\n glyphName: str,\n transformation: DecomposedTransform,\n location: Dict[str, float],\n ) -> None:\n """Add a VarComponent sub glyph. The 'transformation' argument\n must be a DecomposedTransform from the fontTools.misc.transform module,\n and the 'location' argument must be a dictionary mapping axis tags\n to their locations.\n """\n # GlyphSet decomposes for us\n raise AttributeError\n\n\nclass NullPen(AbstractPen):\n """A pen that does nothing."""\n\n def moveTo(self, pt):\n pass\n\n def lineTo(self, pt):\n pass\n\n def curveTo(self, *points):\n pass\n\n def qCurveTo(self, *points):\n pass\n\n def closePath(self):\n pass\n\n def endPath(self):\n pass\n\n def addComponent(self, glyphName, transformation):\n pass\n\n def addVarComponent(self, glyphName, transformation, location):\n pass\n\n\nclass LoggingPen(LogMixin, AbstractPen):\n """A pen with a ``log`` property (see fontTools.misc.loggingTools.LogMixin)"""\n\n pass\n\n\nclass MissingComponentError(KeyError):\n """Indicates a component pointing to a non-existent glyph in the glyphset."""\n\n\nclass DecomposingPen(LoggingPen):\n """Implements a 'addComponent' method that decomposes components\n (i.e. draws them onto self as simple contours).\n It can also be used as a mixin class (e.g. see ContourRecordingPen).\n\n You must override moveTo, lineTo, curveTo and qCurveTo. You may\n additionally override closePath, endPath and addComponent.\n\n By default a warning message is logged when a base glyph is missing;\n set the class variable ``skipMissingComponents`` to False if you want\n all instances of a sub-class to raise a :class:`MissingComponentError`\n exception by default.\n """\n\n skipMissingComponents = True\n # alias error for convenience\n MissingComponentError = MissingComponentError\n\n def __init__(\n self,\n glyphSet,\n *args,\n skipMissingComponents=None,\n reverseFlipped=False,\n **kwargs,\n ):\n """Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced\n as components are looked up by their name.\n\n If the optional 'reverseFlipped' argument is True, components whose transformation\n matrix has a negative determinant will be decomposed with a reversed path direction\n to compensate for the flip.\n\n The optional 'skipMissingComponents' argument can be set to True/False to\n override the homonymous class attribute for a given pen instance.\n """\n super(DecomposingPen, self).__init__(*args, **kwargs)\n self.glyphSet = glyphSet\n self.skipMissingComponents = (\n self.__class__.skipMissingComponents\n if skipMissingComponents is None\n else skipMissingComponents\n )\n self.reverseFlipped = reverseFlipped\n\n def addComponent(self, glyphName, transformation):\n """Transform the points of the base glyph and draw it onto self."""\n from fontTools.pens.transformPen import TransformPen\n\n try:\n glyph = self.glyphSet[glyphName]\n except KeyError:\n if not self.skipMissingComponents:\n raise MissingComponentError(glyphName)\n self.log.warning("glyph '%s' is missing from glyphSet; skipped" % glyphName)\n else:\n pen = self\n if transformation != Identity:\n pen = TransformPen(pen, transformation)\n if self.reverseFlipped:\n # if the transformation has a negative determinant, it will\n # reverse the contour direction of the component\n a, b, c, d = transformation[:4]\n det = a * d - b * c\n if det < 0:\n from fontTools.pens.reverseContourPen import ReverseContourPen\n\n pen = ReverseContourPen(pen)\n glyph.draw(pen)\n\n def addVarComponent(self, glyphName, transformation, location):\n # GlyphSet decomposes for us\n raise AttributeError\n\n\nclass BasePen(DecomposingPen):\n """Base class for drawing pens. You must override _moveTo, _lineTo and\n _curveToOne. You may additionally override _closePath, _endPath,\n addComponent, addVarComponent, and/or _qCurveToOne. You should not\n override any other methods.\n """\n\n def __init__(self, glyphSet=None):\n super(BasePen, self).__init__(glyphSet)\n self.__currentPoint = None\n\n # must override\n\n def _moveTo(self, pt):\n raise NotImplementedError\n\n def _lineTo(self, pt):\n raise NotImplementedError\n\n def _curveToOne(self, pt1, pt2, pt3):\n raise NotImplementedError\n\n # may override\n\n def _closePath(self):\n pass\n\n def _endPath(self):\n pass\n\n def _qCurveToOne(self, pt1, pt2):\n """This method implements the basic quadratic curve type. The\n default implementation delegates the work to the cubic curve\n function. Optionally override with a native implementation.\n """\n pt0x, pt0y = self.__currentPoint\n pt1x, pt1y = pt1\n pt2x, pt2y = pt2\n mid1x = pt0x + 0.66666666666666667 * (pt1x - pt0x)\n mid1y = pt0y + 0.66666666666666667 * (pt1y - pt0y)\n mid2x = pt2x + 0.66666666666666667 * (pt1x - pt2x)\n mid2y = pt2y + 0.66666666666666667 * (pt1y - pt2y)\n self._curveToOne((mid1x, mid1y), (mid2x, mid2y), pt2)\n\n # don't override\n\n def _getCurrentPoint(self):\n """Return the current point. This is not part of the public\n interface, yet is useful for subclasses.\n """\n return self.__currentPoint\n\n def closePath(self):\n self._closePath()\n self.__currentPoint = None\n\n def endPath(self):\n self._endPath()\n self.__currentPoint = None\n\n def moveTo(self, pt):\n self._moveTo(pt)\n self.__currentPoint = pt\n\n def lineTo(self, pt):\n self._lineTo(pt)\n self.__currentPoint = pt\n\n def curveTo(self, *points):\n n = len(points) - 1 # 'n' is the number of control points\n assert n >= 0\n if n == 2:\n # The common case, we have exactly two BCP's, so this is a standard\n # cubic bezier. Even though decomposeSuperBezierSegment() handles\n # this case just fine, we special-case it anyway since it's so\n # common.\n self._curveToOne(*points)\n self.__currentPoint = points[-1]\n elif n > 2:\n # n is the number of control points; split curve into n-1 cubic\n # bezier segments. The algorithm used here is inspired by NURB\n # splines and the TrueType "implied point" principle, and ensures\n # the smoothest possible connection between two curve segments,\n # with no disruption in the curvature. It is practical since it\n # allows one to construct multiple bezier segments with a much\n # smaller amount of points.\n _curveToOne = self._curveToOne\n for pt1, pt2, pt3 in decomposeSuperBezierSegment(points):\n _curveToOne(pt1, pt2, pt3)\n self.__currentPoint = pt3\n elif n == 1:\n self.qCurveTo(*points)\n elif n == 0:\n self.lineTo(points[0])\n else:\n raise AssertionError("can't get there from here")\n\n def qCurveTo(self, *points):\n n = len(points) - 1 # 'n' is the number of control points\n assert n >= 0\n if points[-1] is None:\n # Special case for TrueType quadratics: it is possible to\n # define a contour with NO on-curve points. BasePen supports\n # this by allowing the final argument (the expected on-curve\n # point) to be None. We simulate the feature by making the implied\n # on-curve point between the last and the first off-curve points\n # explicit.\n x, y = points[-2] # last off-curve point\n nx, ny = points[0] # first off-curve point\n impliedStartPoint = (0.5 * (x + nx), 0.5 * (y + ny))\n self.__currentPoint = impliedStartPoint\n self._moveTo(impliedStartPoint)\n points = points[:-1] + (impliedStartPoint,)\n if n > 0:\n # Split the string of points into discrete quadratic curve\n # segments. Between any two consecutive off-curve points\n # there's an implied on-curve point exactly in the middle.\n # This is where the segment splits.\n _qCurveToOne = self._qCurveToOne\n for pt1, pt2 in decomposeQuadraticSegment(points):\n _qCurveToOne(pt1, pt2)\n self.__currentPoint = pt2\n else:\n self.lineTo(points[0])\n\n\ndef decomposeSuperBezierSegment(points):\n """Split the SuperBezier described by 'points' into a list of regular\n bezier segments. The 'points' argument must be a sequence with length\n 3 or greater, containing (x, y) coordinates. The last point is the\n destination on-curve point, the rest of the points are off-curve points.\n The start point should not be supplied.\n\n This function returns a list of (pt1, pt2, pt3) tuples, which each\n specify a regular curveto-style bezier segment.\n """\n n = len(points) - 1\n assert n > 1\n bezierSegments = []\n pt1, pt2, pt3 = points[0], None, None\n for i in range(2, n + 1):\n # calculate points in between control points.\n nDivisions = min(i, 3, n - i + 2)\n for j in range(1, nDivisions):\n factor = j / nDivisions\n temp1 = points[i - 1]\n temp2 = points[i - 2]\n temp = (\n temp2[0] + factor * (temp1[0] - temp2[0]),\n temp2[1] + factor * (temp1[1] - temp2[1]),\n )\n if pt2 is None:\n pt2 = temp\n else:\n pt3 = (0.5 * (pt2[0] + temp[0]), 0.5 * (pt2[1] + temp[1]))\n bezierSegments.append((pt1, pt2, pt3))\n pt1, pt2, pt3 = temp, None, None\n bezierSegments.append((pt1, points[-2], points[-1]))\n return bezierSegments\n\n\ndef decomposeQuadraticSegment(points):\n """Split the quadratic curve segment described by 'points' into a list\n of "atomic" quadratic segments. The 'points' argument must be a sequence\n with length 2 or greater, containing (x, y) coordinates. The last point\n is the destination on-curve point, the rest of the points are off-curve\n points. The start point should not be supplied.\n\n This function returns a list of (pt1, pt2) tuples, which each specify a\n plain quadratic bezier segment.\n """\n n = len(points) - 1\n assert n > 0\n quadSegments = []\n for i in range(n - 1):\n x, y = points[i]\n nx, ny = points[i + 1]\n impliedPt = (0.5 * (x + nx), 0.5 * (y + ny))\n quadSegments.append((points[i], impliedPt))\n quadSegments.append((points[-2], points[-1]))\n return quadSegments\n\n\nclass _TestPen(BasePen):\n """Test class that prints PostScript to stdout."""\n\n def _moveTo(self, pt):\n print("%s %s moveto" % (pt[0], pt[1]))\n\n def _lineTo(self, pt):\n print("%s %s lineto" % (pt[0], pt[1]))\n\n def _curveToOne(self, bcp1, bcp2, pt):\n print(\n "%s %s %s %s %s %s curveto"\n % (bcp1[0], bcp1[1], bcp2[0], bcp2[1], pt[0], pt[1])\n )\n\n def _closePath(self):\n print("closepath")\n\n\nif __name__ == "__main__":\n pen = _TestPen(None)\n pen.moveTo((0, 0))\n pen.lineTo((0, 100))\n pen.curveTo((50, 75), (60, 50), (50, 25), (0, 0))\n pen.closePath()\n\n pen = _TestPen(None)\n # testing the "no on-curve point" scenario\n pen.qCurveTo((0, 0), (0, 100), (100, 100), (100, 0), None)\n pen.closePath()\n
.venv\Lib\site-packages\fontTools\pens\basePen.py
basePen.py
Python
17,548
0.95
0.204211
0.085938
node-utils
505
2024-02-29T00:17:10.484513
Apache-2.0
false
b992374f5fc9423c4810307be7489763
from fontTools.misc.arrayTools import updateBounds, pointInRect, unionRect\nfrom fontTools.misc.bezierTools import calcCubicBounds, calcQuadraticBounds\nfrom fontTools.pens.basePen import BasePen\n\n\n__all__ = ["BoundsPen", "ControlBoundsPen"]\n\n\nclass ControlBoundsPen(BasePen):\n """Pen to calculate the "control bounds" of a shape. This is the\n bounding box of all control points, so may be larger than the\n actual bounding box if there are curves that don't have points\n on their extremes.\n\n When the shape has been drawn, the bounds are available as the\n ``bounds`` attribute of the pen object. It's a 4-tuple::\n\n (xMin, yMin, xMax, yMax).\n\n If ``ignoreSinglePoints`` is True, single points are ignored.\n """\n\n def __init__(self, glyphSet, ignoreSinglePoints=False):\n BasePen.__init__(self, glyphSet)\n self.ignoreSinglePoints = ignoreSinglePoints\n self.init()\n\n def init(self):\n self.bounds = None\n self._start = None\n\n def _moveTo(self, pt):\n self._start = pt\n if not self.ignoreSinglePoints:\n self._addMoveTo()\n\n def _addMoveTo(self):\n if self._start is None:\n return\n bounds = self.bounds\n if bounds:\n self.bounds = updateBounds(bounds, self._start)\n else:\n x, y = self._start\n self.bounds = (x, y, x, y)\n self._start = None\n\n def _lineTo(self, pt):\n self._addMoveTo()\n self.bounds = updateBounds(self.bounds, pt)\n\n def _curveToOne(self, bcp1, bcp2, pt):\n self._addMoveTo()\n bounds = self.bounds\n bounds = updateBounds(bounds, bcp1)\n bounds = updateBounds(bounds, bcp2)\n bounds = updateBounds(bounds, pt)\n self.bounds = bounds\n\n def _qCurveToOne(self, bcp, pt):\n self._addMoveTo()\n bounds = self.bounds\n bounds = updateBounds(bounds, bcp)\n bounds = updateBounds(bounds, pt)\n self.bounds = bounds\n\n\nclass BoundsPen(ControlBoundsPen):\n """Pen to calculate the bounds of a shape. It calculates the\n correct bounds even when the shape contains curves that don't\n have points on their extremes. This is somewhat slower to compute\n than the "control bounds".\n\n When the shape has been drawn, the bounds are available as the\n ``bounds`` attribute of the pen object. It's a 4-tuple::\n\n (xMin, yMin, xMax, yMax)\n """\n\n def _curveToOne(self, bcp1, bcp2, pt):\n self._addMoveTo()\n bounds = self.bounds\n bounds = updateBounds(bounds, pt)\n if not pointInRect(bcp1, bounds) or not pointInRect(bcp2, bounds):\n bounds = unionRect(\n bounds, calcCubicBounds(self._getCurrentPoint(), bcp1, bcp2, pt)\n )\n self.bounds = bounds\n\n def _qCurveToOne(self, bcp, pt):\n self._addMoveTo()\n bounds = self.bounds\n bounds = updateBounds(bounds, pt)\n if not pointInRect(bcp, bounds):\n bounds = unionRect(\n bounds, calcQuadraticBounds(self._getCurrentPoint(), bcp, pt)\n )\n self.bounds = bounds\n
.venv\Lib\site-packages\fontTools\pens\boundsPen.py
boundsPen.py
Python
3,227
0.85
0.173469
0
vue-tools
803
2024-05-17T04:42:42.222229
BSD-3-Clause
false
53bd5d5988f79211d2b3c3ae0d8ccdfe
"""Pen to draw to a Cairo graphics library context."""\n\nfrom fontTools.pens.basePen import BasePen\n\n\n__all__ = ["CairoPen"]\n\n\nclass CairoPen(BasePen):\n """Pen to draw to a Cairo graphics library context."""\n\n def __init__(self, glyphSet, context):\n BasePen.__init__(self, glyphSet)\n self.context = context\n\n def _moveTo(self, p):\n self.context.move_to(*p)\n\n def _lineTo(self, p):\n self.context.line_to(*p)\n\n def _curveToOne(self, p1, p2, p3):\n self.context.curve_to(*p1, *p2, *p3)\n\n def _closePath(self):\n self.context.close_path()\n
.venv\Lib\site-packages\fontTools\pens\cairoPen.py
cairoPen.py
Python
618
0.85
0.230769
0
awesome-app
672
2023-09-13T07:52:38.088096
GPL-3.0
false
5a7263d6079aec8b3e0a5984f55f568b
from fontTools.pens.basePen import BasePen\n\n\n__all__ = ["CocoaPen"]\n\n\nclass CocoaPen(BasePen):\n def __init__(self, glyphSet, path=None):\n BasePen.__init__(self, glyphSet)\n if path is None:\n from AppKit import NSBezierPath\n\n path = NSBezierPath.bezierPath()\n self.path = path\n\n def _moveTo(self, p):\n self.path.moveToPoint_(p)\n\n def _lineTo(self, p):\n self.path.lineToPoint_(p)\n\n def _curveToOne(self, p1, p2, p3):\n self.path.curveToPoint_controlPoint1_controlPoint2_(p3, p1, p2)\n\n def _closePath(self):\n self.path.closePath()\n
.venv\Lib\site-packages\fontTools\pens\cocoaPen.py
cocoaPen.py
Python
638
0.85
0.269231
0
vue-tools
202
2025-06-11T03:30:41.799775
MIT
false
222b3630c952055c4e1eaa521eea9ad8
# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport operator\nfrom fontTools.cu2qu import curve_to_quadratic, curves_to_quadratic\nfrom fontTools.pens.basePen import decomposeSuperBezierSegment\nfrom fontTools.pens.filterPen import FilterPen\nfrom fontTools.pens.reverseContourPen import ReverseContourPen\nfrom fontTools.pens.pointPen import BasePointToSegmentPen\nfrom fontTools.pens.pointPen import ReverseContourPointPen\n\n\nclass Cu2QuPen(FilterPen):\n """A filter pen to convert cubic bezier curves to quadratic b-splines\n using the FontTools SegmentPen protocol.\n\n Args:\n\n other_pen: another SegmentPen used to draw the transformed outline.\n max_err: maximum approximation error in font units. For optimal results,\n if you know the UPEM of the font, we recommend setting this to a\n value equal, or close to UPEM / 1000.\n reverse_direction: flip the contours' direction but keep starting point.\n stats: a dictionary counting the point numbers of quadratic segments.\n all_quadratic: if True (default), only quadratic b-splines are generated.\n if False, quadratic curves or cubic curves are generated depending\n on which one is more economical.\n """\n\n def __init__(\n self,\n other_pen,\n max_err,\n reverse_direction=False,\n stats=None,\n all_quadratic=True,\n ):\n if reverse_direction:\n other_pen = ReverseContourPen(other_pen)\n super().__init__(other_pen)\n self.max_err = max_err\n self.stats = stats\n self.all_quadratic = all_quadratic\n\n def _convert_curve(self, pt1, pt2, pt3):\n curve = (self.current_pt, pt1, pt2, pt3)\n result = curve_to_quadratic(curve, self.max_err, self.all_quadratic)\n if self.stats is not None:\n n = str(len(result) - 2)\n self.stats[n] = self.stats.get(n, 0) + 1\n if self.all_quadratic:\n self.qCurveTo(*result[1:])\n else:\n if len(result) == 3:\n self.qCurveTo(*result[1:])\n else:\n assert len(result) == 4\n super().curveTo(*result[1:])\n\n def curveTo(self, *points):\n n = len(points)\n if n == 3:\n # this is the most common case, so we special-case it\n self._convert_curve(*points)\n elif n > 3:\n for segment in decomposeSuperBezierSegment(points):\n self._convert_curve(*segment)\n else:\n self.qCurveTo(*points)\n\n\nclass Cu2QuPointPen(BasePointToSegmentPen):\n """A filter pen to convert cubic bezier curves to quadratic b-splines\n using the FontTools PointPen protocol.\n\n Args:\n other_point_pen: another PointPen used to draw the transformed outline.\n max_err: maximum approximation error in font units. For optimal results,\n if you know the UPEM of the font, we recommend setting this to a\n value equal, or close to UPEM / 1000.\n reverse_direction: reverse the winding direction of all contours.\n stats: a dictionary counting the point numbers of quadratic segments.\n all_quadratic: if True (default), only quadratic b-splines are generated.\n if False, quadratic curves or cubic curves are generated depending\n on which one is more economical.\n """\n\n __points_required = {\n "move": (1, operator.eq),\n "line": (1, operator.eq),\n "qcurve": (2, operator.ge),\n "curve": (3, operator.eq),\n }\n\n def __init__(\n self,\n other_point_pen,\n max_err,\n reverse_direction=False,\n stats=None,\n all_quadratic=True,\n ):\n BasePointToSegmentPen.__init__(self)\n if reverse_direction:\n self.pen = ReverseContourPointPen(other_point_pen)\n else:\n self.pen = other_point_pen\n self.max_err = max_err\n self.stats = stats\n self.all_quadratic = all_quadratic\n\n def _flushContour(self, segments):\n assert len(segments) >= 1\n closed = segments[0][0] != "move"\n new_segments = []\n prev_points = segments[-1][1]\n prev_on_curve = prev_points[-1][0]\n for segment_type, points in segments:\n if segment_type == "curve":\n for sub_points in self._split_super_bezier_segments(points):\n on_curve, smooth, name, kwargs = sub_points[-1]\n bcp1, bcp2 = sub_points[0][0], sub_points[1][0]\n cubic = [prev_on_curve, bcp1, bcp2, on_curve]\n quad = curve_to_quadratic(cubic, self.max_err, self.all_quadratic)\n if self.stats is not None:\n n = str(len(quad) - 2)\n self.stats[n] = self.stats.get(n, 0) + 1\n new_points = [(pt, False, None, {}) for pt in quad[1:-1]]\n new_points.append((on_curve, smooth, name, kwargs))\n if self.all_quadratic or len(new_points) == 2:\n new_segments.append(["qcurve", new_points])\n else:\n new_segments.append(["curve", new_points])\n prev_on_curve = sub_points[-1][0]\n else:\n new_segments.append([segment_type, points])\n prev_on_curve = points[-1][0]\n if closed:\n # the BasePointToSegmentPen.endPath method that calls _flushContour\n # rotates the point list of closed contours so that they end with\n # the first on-curve point. We restore the original starting point.\n new_segments = new_segments[-1:] + new_segments[:-1]\n self._drawPoints(new_segments)\n\n def _split_super_bezier_segments(self, points):\n sub_segments = []\n # n is the number of control points\n n = len(points) - 1\n if n == 2:\n # a simple bezier curve segment\n sub_segments.append(points)\n elif n > 2:\n # a "super" bezier; decompose it\n on_curve, smooth, name, kwargs = points[-1]\n num_sub_segments = n - 1\n for i, sub_points in enumerate(\n decomposeSuperBezierSegment([pt for pt, _, _, _ in points])\n ):\n new_segment = []\n for point in sub_points[:-1]:\n new_segment.append((point, False, None, {}))\n if i == (num_sub_segments - 1):\n # the last on-curve keeps its original attributes\n new_segment.append((on_curve, smooth, name, kwargs))\n else:\n # on-curves of sub-segments are always "smooth"\n new_segment.append((sub_points[-1], True, None, {}))\n sub_segments.append(new_segment)\n else:\n raise AssertionError("expected 2 control points, found: %d" % n)\n return sub_segments\n\n def _drawPoints(self, segments):\n pen = self.pen\n pen.beginPath()\n last_offcurves = []\n points_required = self.__points_required\n for i, (segment_type, points) in enumerate(segments):\n if segment_type in points_required:\n n, op = points_required[segment_type]\n assert op(len(points), n), (\n f"illegal {segment_type!r} segment point count: "\n f"expected {n}, got {len(points)}"\n )\n offcurves = points[:-1]\n if i == 0:\n # any off-curve points preceding the first on-curve\n # will be appended at the end of the contour\n last_offcurves = offcurves\n else:\n for pt, smooth, name, kwargs in offcurves:\n pen.addPoint(pt, None, smooth, name, **kwargs)\n pt, smooth, name, kwargs = points[-1]\n if pt is None:\n assert segment_type == "qcurve"\n # special quadratic contour with no on-curve points:\n # we need to skip the "None" point. See also the Pen\n # protocol's qCurveTo() method and fontTools.pens.basePen\n pass\n else:\n pen.addPoint(pt, segment_type, smooth, name, **kwargs)\n else:\n raise AssertionError("unexpected segment type: %r" % segment_type)\n for pt, smooth, name, kwargs in last_offcurves:\n pen.addPoint(pt, None, smooth, name, **kwargs)\n pen.endPath()\n\n def addComponent(self, baseGlyphName, transformation):\n assert self.currentPath is None\n self.pen.addComponent(baseGlyphName, transformation)\n\n\nclass Cu2QuMultiPen:\n """A filter multi-pen to convert cubic bezier curves to quadratic b-splines\n in a interpolation-compatible manner, using the FontTools SegmentPen protocol.\n\n Args:\n\n other_pens: list of SegmentPens used to draw the transformed outlines.\n max_err: maximum approximation error in font units. For optimal results,\n if you know the UPEM of the font, we recommend setting this to a\n value equal, or close to UPEM / 1000.\n reverse_direction: flip the contours' direction but keep starting point.\n\n This pen does not follow the normal SegmentPen protocol. Instead, its\n moveTo/lineTo/qCurveTo/curveTo methods take a list of tuples that are\n arguments that would normally be passed to a SegmentPen, one item for\n each of the pens in other_pens.\n """\n\n # TODO Simplify like 3e8ebcdce592fe8a59ca4c3a294cc9724351e1ce\n # Remove start_pts and _add_moveTO\n\n def __init__(self, other_pens, max_err, reverse_direction=False):\n if reverse_direction:\n other_pens = [\n ReverseContourPen(pen, outputImpliedClosingLine=True)\n for pen in other_pens\n ]\n self.pens = other_pens\n self.max_err = max_err\n self.start_pts = None\n self.current_pts = None\n\n def _check_contour_is_open(self):\n if self.current_pts is None:\n raise AssertionError("moveTo is required")\n\n def _check_contour_is_closed(self):\n if self.current_pts is not None:\n raise AssertionError("closePath or endPath is required")\n\n def _add_moveTo(self):\n if self.start_pts is not None:\n for pt, pen in zip(self.start_pts, self.pens):\n pen.moveTo(*pt)\n self.start_pts = None\n\n def moveTo(self, pts):\n self._check_contour_is_closed()\n self.start_pts = self.current_pts = pts\n self._add_moveTo()\n\n def lineTo(self, pts):\n self._check_contour_is_open()\n self._add_moveTo()\n for pt, pen in zip(pts, self.pens):\n pen.lineTo(*pt)\n self.current_pts = pts\n\n def qCurveTo(self, pointsList):\n self._check_contour_is_open()\n if len(pointsList[0]) == 1:\n self.lineTo([(points[0],) for points in pointsList])\n return\n self._add_moveTo()\n current_pts = []\n for points, pen in zip(pointsList, self.pens):\n pen.qCurveTo(*points)\n current_pts.append((points[-1],))\n self.current_pts = current_pts\n\n def _curves_to_quadratic(self, pointsList):\n curves = []\n for current_pt, points in zip(self.current_pts, pointsList):\n curves.append(current_pt + points)\n quadratics = curves_to_quadratic(curves, [self.max_err] * len(curves))\n pointsList = []\n for quadratic in quadratics:\n pointsList.append(quadratic[1:])\n self.qCurveTo(pointsList)\n\n def curveTo(self, pointsList):\n self._check_contour_is_open()\n self._curves_to_quadratic(pointsList)\n\n def closePath(self):\n self._check_contour_is_open()\n if self.start_pts is None:\n for pen in self.pens:\n pen.closePath()\n self.current_pts = self.start_pts = None\n\n def endPath(self):\n self._check_contour_is_open()\n if self.start_pts is None:\n for pen in self.pens:\n pen.endPath()\n self.current_pts = self.start_pts = None\n\n def addComponent(self, glyphName, transformations):\n self._check_contour_is_closed()\n for trans, pen in zip(transformations, self.pens):\n pen.addComponent(glyphName, trans)\n
.venv\Lib\site-packages\fontTools\pens\cu2quPen.py
cu2quPen.py
Python
13,332
0.95
0.227692
0.1
vue-tools
216
2024-06-06T06:07:58.502018
GPL-3.0
false
7f9170287e93c249db11d5345f242586
from fontTools.pens.filterPen import ContourFilterPen\n\n\nclass ExplicitClosingLinePen(ContourFilterPen):\n """A filter pen that adds an explicit lineTo to the first point of each closed\n contour if the end point of the last segment is not already the same as the first point.\n Otherwise, it passes the contour through unchanged.\n\n >>> from pprint import pprint\n >>> from fontTools.pens.recordingPen import RecordingPen\n >>> rec = RecordingPen()\n >>> pen = ExplicitClosingLinePen(rec)\n >>> pen.moveTo((0, 0))\n >>> pen.lineTo((100, 0))\n >>> pen.lineTo((100, 100))\n >>> pen.closePath()\n >>> pprint(rec.value)\n [('moveTo', ((0, 0),)),\n ('lineTo', ((100, 0),)),\n ('lineTo', ((100, 100),)),\n ('lineTo', ((0, 0),)),\n ('closePath', ())]\n >>> rec = RecordingPen()\n >>> pen = ExplicitClosingLinePen(rec)\n >>> pen.moveTo((0, 0))\n >>> pen.lineTo((100, 0))\n >>> pen.lineTo((100, 100))\n >>> pen.lineTo((0, 0))\n >>> pen.closePath()\n >>> pprint(rec.value)\n [('moveTo', ((0, 0),)),\n ('lineTo', ((100, 0),)),\n ('lineTo', ((100, 100),)),\n ('lineTo', ((0, 0),)),\n ('closePath', ())]\n >>> rec = RecordingPen()\n >>> pen = ExplicitClosingLinePen(rec)\n >>> pen.moveTo((0, 0))\n >>> pen.curveTo((100, 0), (0, 100), (100, 100))\n >>> pen.closePath()\n >>> pprint(rec.value)\n [('moveTo', ((0, 0),)),\n ('curveTo', ((100, 0), (0, 100), (100, 100))),\n ('lineTo', ((0, 0),)),\n ('closePath', ())]\n >>> rec = RecordingPen()\n >>> pen = ExplicitClosingLinePen(rec)\n >>> pen.moveTo((0, 0))\n >>> pen.curveTo((100, 0), (0, 100), (100, 100))\n >>> pen.lineTo((0, 0))\n >>> pen.closePath()\n >>> pprint(rec.value)\n [('moveTo', ((0, 0),)),\n ('curveTo', ((100, 0), (0, 100), (100, 100))),\n ('lineTo', ((0, 0),)),\n ('closePath', ())]\n >>> rec = RecordingPen()\n >>> pen = ExplicitClosingLinePen(rec)\n >>> pen.moveTo((0, 0))\n >>> pen.curveTo((100, 0), (0, 100), (0, 0))\n >>> pen.closePath()\n >>> pprint(rec.value)\n [('moveTo', ((0, 0),)),\n ('curveTo', ((100, 0), (0, 100), (0, 0))),\n ('closePath', ())]\n >>> rec = RecordingPen()\n >>> pen = ExplicitClosingLinePen(rec)\n >>> pen.moveTo((0, 0))\n >>> pen.closePath()\n >>> pprint(rec.value)\n [('moveTo', ((0, 0),)), ('closePath', ())]\n >>> rec = RecordingPen()\n >>> pen = ExplicitClosingLinePen(rec)\n >>> pen.closePath()\n >>> pprint(rec.value)\n [('closePath', ())]\n >>> rec = RecordingPen()\n >>> pen = ExplicitClosingLinePen(rec)\n >>> pen.moveTo((0, 0))\n >>> pen.lineTo((100, 0))\n >>> pen.lineTo((100, 100))\n >>> pen.endPath()\n >>> pprint(rec.value)\n [('moveTo', ((0, 0),)),\n ('lineTo', ((100, 0),)),\n ('lineTo', ((100, 100),)),\n ('endPath', ())]\n """\n\n def filterContour(self, contour):\n if (\n not contour\n or contour[0][0] != "moveTo"\n or contour[-1][0] != "closePath"\n or len(contour) < 3\n ):\n return\n movePt = contour[0][1][0]\n lastSeg = contour[-2][1]\n if lastSeg and movePt != lastSeg[-1]:\n contour[-1:] = [("lineTo", (movePt,)), ("closePath", ())]\n
.venv\Lib\site-packages\fontTools\pens\explicitClosingLinePen.py
explicitClosingLinePen.py
Python
3,320
0.85
0.049505
0
vue-tools
883
2024-09-14T20:27:20.694687
BSD-3-Clause
false
560eaab6bcb72e1697484de656efa170
from __future__ import annotations\n\nfrom fontTools.pens.basePen import AbstractPen, DecomposingPen\nfrom fontTools.pens.pointPen import AbstractPointPen, DecomposingPointPen\nfrom fontTools.pens.recordingPen import RecordingPen\n\n\nclass _PassThruComponentsMixin(object):\n def addComponent(self, glyphName, transformation, **kwargs):\n self._outPen.addComponent(glyphName, transformation, **kwargs)\n\n\nclass FilterPen(_PassThruComponentsMixin, AbstractPen):\n """Base class for pens that apply some transformation to the coordinates\n they receive and pass them to another pen.\n\n You can override any of its methods. The default implementation does\n nothing, but passes the commands unmodified to the other pen.\n\n >>> from fontTools.pens.recordingPen import RecordingPen\n >>> rec = RecordingPen()\n >>> pen = FilterPen(rec)\n >>> v = iter(rec.value)\n\n >>> pen.moveTo((0, 0))\n >>> next(v)\n ('moveTo', ((0, 0),))\n\n >>> pen.lineTo((1, 1))\n >>> next(v)\n ('lineTo', ((1, 1),))\n\n >>> pen.curveTo((2, 2), (3, 3), (4, 4))\n >>> next(v)\n ('curveTo', ((2, 2), (3, 3), (4, 4)))\n\n >>> pen.qCurveTo((5, 5), (6, 6), (7, 7), (8, 8))\n >>> next(v)\n ('qCurveTo', ((5, 5), (6, 6), (7, 7), (8, 8)))\n\n >>> pen.closePath()\n >>> next(v)\n ('closePath', ())\n\n >>> pen.moveTo((9, 9))\n >>> next(v)\n ('moveTo', ((9, 9),))\n\n >>> pen.endPath()\n >>> next(v)\n ('endPath', ())\n\n >>> pen.addComponent('foo', (1, 0, 0, 1, 0, 0))\n >>> next(v)\n ('addComponent', ('foo', (1, 0, 0, 1, 0, 0)))\n """\n\n def __init__(self, outPen):\n self._outPen = outPen\n self.current_pt = None\n\n def moveTo(self, pt):\n self._outPen.moveTo(pt)\n self.current_pt = pt\n\n def lineTo(self, pt):\n self._outPen.lineTo(pt)\n self.current_pt = pt\n\n def curveTo(self, *points):\n self._outPen.curveTo(*points)\n self.current_pt = points[-1]\n\n def qCurveTo(self, *points):\n self._outPen.qCurveTo(*points)\n self.current_pt = points[-1]\n\n def closePath(self):\n self._outPen.closePath()\n self.current_pt = None\n\n def endPath(self):\n self._outPen.endPath()\n self.current_pt = None\n\n\nclass ContourFilterPen(_PassThruComponentsMixin, RecordingPen):\n """A "buffered" filter pen that accumulates contour data, passes\n it through a ``filterContour`` method when the contour is closed or ended,\n and finally draws the result with the output pen.\n\n Components are passed through unchanged.\n """\n\n def __init__(self, outPen):\n super(ContourFilterPen, self).__init__()\n self._outPen = outPen\n\n def closePath(self):\n super(ContourFilterPen, self).closePath()\n self._flushContour()\n\n def endPath(self):\n super(ContourFilterPen, self).endPath()\n self._flushContour()\n\n def _flushContour(self):\n result = self.filterContour(self.value)\n if result is not None:\n self.value = result\n self.replay(self._outPen)\n self.value = []\n\n def filterContour(self, contour):\n """Subclasses must override this to perform the filtering.\n\n The contour is a list of pen (operator, operands) tuples.\n Operators are strings corresponding to the AbstractPen methods:\n "moveTo", "lineTo", "curveTo", "qCurveTo", "closePath" and\n "endPath". The operands are the positional arguments that are\n passed to each method.\n\n If the method doesn't return a value (i.e. returns None), it's\n assumed that the argument was modified in-place.\n Otherwise, the return value is drawn with the output pen.\n """\n return # or return contour\n\n\nclass FilterPointPen(_PassThruComponentsMixin, AbstractPointPen):\n """Baseclass for point pens that apply some transformation to the\n coordinates they receive and pass them to another point pen.\n\n You can override any of its methods. The default implementation does\n nothing, but passes the commands unmodified to the other pen.\n\n >>> from fontTools.pens.recordingPen import RecordingPointPen\n >>> rec = RecordingPointPen()\n >>> pen = FilterPointPen(rec)\n >>> v = iter(rec.value)\n >>> pen.beginPath(identifier="abc")\n >>> next(v)\n ('beginPath', (), {'identifier': 'abc'})\n >>> pen.addPoint((1, 2), "line", False)\n >>> next(v)\n ('addPoint', ((1, 2), 'line', False, None), {})\n >>> pen.addComponent("a", (2, 0, 0, 2, 10, -10), identifier="0001")\n >>> next(v)\n ('addComponent', ('a', (2, 0, 0, 2, 10, -10)), {'identifier': '0001'})\n >>> pen.endPath()\n >>> next(v)\n ('endPath', (), {})\n """\n\n def __init__(self, outPen):\n self._outPen = outPen\n\n def beginPath(self, **kwargs):\n self._outPen.beginPath(**kwargs)\n\n def endPath(self):\n self._outPen.endPath()\n\n def addPoint(self, pt, segmentType=None, smooth=False, name=None, **kwargs):\n self._outPen.addPoint(pt, segmentType, smooth, name, **kwargs)\n\n\nclass _DecomposingFilterPenMixin:\n """Mixin class that decomposes components as regular contours.\n\n Shared by both DecomposingFilterPen and DecomposingFilterPointPen.\n\n Takes two required parameters, another (segment or point) pen 'outPen' to draw\n with, and a 'glyphSet' dict of drawable glyph objects to draw components from.\n\n The 'skipMissingComponents' and 'reverseFlipped' optional arguments work the\n same as in the DecomposingPen/DecomposingPointPen. Both are False by default.\n\n In addition, the decomposing filter pens also take the following two options:\n\n 'include' is an optional set of component base glyph names to consider for\n decomposition; the default include=None means decompose all components no matter\n the base glyph name).\n\n 'decomposeNested' (bool) controls whether to recurse decomposition into nested\n components of components (this only matters when 'include' was also provided);\n if False, only decompose top-level components included in the set, but not\n also their children.\n """\n\n # raises MissingComponentError if base glyph is not found in glyphSet\n skipMissingComponents = False\n\n def __init__(\n self,\n outPen,\n glyphSet,\n skipMissingComponents=None,\n reverseFlipped=False,\n include: set[str] | None = None,\n decomposeNested: bool = True,\n ):\n super().__init__(\n outPen=outPen,\n glyphSet=glyphSet,\n skipMissingComponents=skipMissingComponents,\n reverseFlipped=reverseFlipped,\n )\n self.include = include\n self.decomposeNested = decomposeNested\n\n def addComponent(self, baseGlyphName, transformation, **kwargs):\n # only decompose the component if it's included in the set\n if self.include is None or baseGlyphName in self.include:\n # if we're decomposing nested components, temporarily set include to None\n include_bak = self.include\n if self.decomposeNested and self.include:\n self.include = None\n try:\n super().addComponent(baseGlyphName, transformation, **kwargs)\n finally:\n if self.include != include_bak:\n self.include = include_bak\n else:\n _PassThruComponentsMixin.addComponent(\n self, baseGlyphName, transformation, **kwargs\n )\n\n\nclass DecomposingFilterPen(_DecomposingFilterPenMixin, DecomposingPen, FilterPen):\n """Filter pen that draws components as regular contours."""\n\n pass\n\n\nclass DecomposingFilterPointPen(\n _DecomposingFilterPenMixin, DecomposingPointPen, FilterPointPen\n):\n """Filter point pen that draws components as regular contours."""\n\n pass\n
.venv\Lib\site-packages\fontTools\pens\filterPen.py
filterPen.py
Python
8,031
0.95
0.165975
0.016304
react-lib
43
2024-03-27T07:10:26.626117
BSD-3-Clause
false
ca6ee0ed277147031c0c16d223c040b2
# -*- coding: utf-8 -*-\n\n"""Pen to rasterize paths with FreeType."""\n\n__all__ = ["FreeTypePen"]\n\nimport os\nimport ctypes\nimport platform\nimport subprocess\nimport collections\nimport math\n\nimport freetype\nfrom freetype.raw import FT_Outline_Get_Bitmap, FT_Outline_Get_BBox, FT_Outline_Get_CBox\nfrom freetype.ft_types import FT_Pos\nfrom freetype.ft_structs import FT_Vector, FT_BBox, FT_Bitmap, FT_Outline\nfrom freetype.ft_enums import (\n FT_OUTLINE_NONE,\n FT_OUTLINE_EVEN_ODD_FILL,\n FT_PIXEL_MODE_GRAY,\n FT_CURVE_TAG_ON,\n FT_CURVE_TAG_CONIC,\n FT_CURVE_TAG_CUBIC,\n)\nfrom freetype.ft_errors import FT_Exception\n\nfrom fontTools.pens.basePen import BasePen, PenError\nfrom fontTools.misc.roundTools import otRound\nfrom fontTools.misc.transform import Transform\n\nContour = collections.namedtuple("Contour", ("points", "tags"))\n\n\nclass FreeTypePen(BasePen):\n """Pen to rasterize paths with FreeType. Requires `freetype-py` module.\n\n Constructs ``FT_Outline`` from the paths, and renders it within a bitmap\n buffer.\n\n For ``array()`` and ``show()``, `numpy` and `matplotlib` must be installed.\n For ``image()``, `Pillow` is required. Each module is lazily loaded when the\n corresponding method is called.\n\n Args:\n glyphSet: a dictionary of drawable glyph objects keyed by name\n used to resolve component references in composite glyphs.\n\n Examples:\n If `numpy` and `matplotlib` is available, the following code will\n show the glyph image of `fi` in a new window::\n\n from fontTools.ttLib import TTFont\n from fontTools.pens.freetypePen import FreeTypePen\n from fontTools.misc.transform import Offset\n pen = FreeTypePen(None)\n font = TTFont('SourceSansPro-Regular.otf')\n glyph = font.getGlyphSet()['fi']\n glyph.draw(pen)\n width, ascender, descender = glyph.width, font['OS/2'].usWinAscent, -font['OS/2'].usWinDescent\n height = ascender - descender\n pen.show(width=width, height=height, transform=Offset(0, -descender))\n\n Combining with `uharfbuzz`, you can typeset a chunk of glyphs in a pen::\n\n import uharfbuzz as hb\n from fontTools.pens.freetypePen import FreeTypePen\n from fontTools.pens.transformPen import TransformPen\n from fontTools.misc.transform import Offset\n\n en1, en2, ar, ja = 'Typesetting', 'Jeff', 'صف الحروف', 'たいぷせっと'\n for text, font_path, direction, typo_ascender, typo_descender, vhea_ascender, vhea_descender, contain, features in (\n (en1, 'NotoSans-Regular.ttf', 'ltr', 2189, -600, None, None, False, {"kern": True, "liga": True}),\n (en2, 'NotoSans-Regular.ttf', 'ltr', 2189, -600, None, None, True, {"kern": True, "liga": True}),\n (ar, 'NotoSansArabic-Regular.ttf', 'rtl', 1374, -738, None, None, False, {"kern": True, "liga": True}),\n (ja, 'NotoSansJP-Regular.otf', 'ltr', 880, -120, 500, -500, False, {"palt": True, "kern": True}),\n (ja, 'NotoSansJP-Regular.otf', 'ttb', 880, -120, 500, -500, False, {"vert": True, "vpal": True, "vkrn": True})\n ):\n blob = hb.Blob.from_file_path(font_path)\n face = hb.Face(blob)\n font = hb.Font(face)\n buf = hb.Buffer()\n buf.direction = direction\n buf.add_str(text)\n buf.guess_segment_properties()\n hb.shape(font, buf, features)\n\n x, y = 0, 0\n pen = FreeTypePen(None)\n for info, pos in zip(buf.glyph_infos, buf.glyph_positions):\n gid = info.codepoint\n transformed = TransformPen(pen, Offset(x + pos.x_offset, y + pos.y_offset))\n font.draw_glyph_with_pen(gid, transformed)\n x += pos.x_advance\n y += pos.y_advance\n\n offset, width, height = None, None, None\n if direction in ('ltr', 'rtl'):\n offset = (0, -typo_descender)\n width = x\n height = typo_ascender - typo_descender\n else:\n offset = (-vhea_descender, -y)\n width = vhea_ascender - vhea_descender\n height = -y\n pen.show(width=width, height=height, transform=Offset(*offset), contain=contain)\n\n For Jupyter Notebook, the rendered image will be displayed in a cell if\n you replace ``show()`` with ``image()`` in the examples.\n """\n\n def __init__(self, glyphSet):\n BasePen.__init__(self, glyphSet)\n self.contours = []\n\n def outline(self, transform=None, evenOdd=False):\n """Converts the current contours to ``FT_Outline``.\n\n Args:\n transform: An optional 6-tuple containing an affine transformation,\n or a ``Transform`` object from the ``fontTools.misc.transform``\n module.\n evenOdd: Pass ``True`` for even-odd fill instead of non-zero.\n """\n transform = transform or Transform()\n if not hasattr(transform, "transformPoint"):\n transform = Transform(*transform)\n n_contours = len(self.contours)\n n_points = sum((len(contour.points) for contour in self.contours))\n points = []\n for contour in self.contours:\n for point in contour.points:\n point = transform.transformPoint(point)\n points.append(\n FT_Vector(\n FT_Pos(otRound(point[0] * 64)), FT_Pos(otRound(point[1] * 64))\n )\n )\n tags = []\n for contour in self.contours:\n for tag in contour.tags:\n tags.append(tag)\n contours = []\n contours_sum = 0\n for contour in self.contours:\n contours_sum += len(contour.points)\n contours.append(contours_sum - 1)\n flags = FT_OUTLINE_EVEN_ODD_FILL if evenOdd else FT_OUTLINE_NONE\n return FT_Outline(\n (ctypes.c_short)(n_contours),\n (ctypes.c_short)(n_points),\n (FT_Vector * n_points)(*points),\n (ctypes.c_ubyte * n_points)(*tags),\n (ctypes.c_short * n_contours)(*contours),\n (ctypes.c_int)(flags),\n )\n\n def buffer(\n self, width=None, height=None, transform=None, contain=False, evenOdd=False\n ):\n """Renders the current contours within a bitmap buffer.\n\n Args:\n width: Image width of the bitmap in pixels. If omitted, it\n automatically fits to the bounding box of the contours.\n height: Image height of the bitmap in pixels. If omitted, it\n automatically fits to the bounding box of the contours.\n transform: An optional 6-tuple containing an affine transformation,\n or a ``Transform`` object from the ``fontTools.misc.transform``\n module. The bitmap size is not affected by this matrix.\n contain: If ``True``, the image size will be automatically expanded\n so that it fits to the bounding box of the paths. Useful for\n rendering glyphs with negative sidebearings without clipping.\n evenOdd: Pass ``True`` for even-odd fill instead of non-zero.\n\n Returns:\n A tuple of ``(buffer, size)``, where ``buffer`` is a ``bytes``\n object of the resulted bitmap and ``size`` is a 2-tuple of its\n dimension.\n\n Notes:\n The image size should always be given explicitly if you need to get\n a proper glyph image. When ``width`` and ``height`` are omitted, it\n forcifully fits to the bounding box and the side bearings get\n cropped. If you pass ``0`` to both ``width`` and ``height`` and set\n ``contain`` to ``True``, it expands to the bounding box while\n maintaining the origin of the contours, meaning that LSB will be\n maintained but RSB won’t. The difference between the two becomes\n more obvious when rotate or skew transformation is applied.\n\n Example:\n .. code-block:: pycon\n\n >>>\n >> pen = FreeTypePen(None)\n >> glyph.draw(pen)\n >> buf, size = pen.buffer(width=500, height=1000)\n >> type(buf), len(buf), size\n (<class 'bytes'>, 500000, (500, 1000))\n """\n transform = transform or Transform()\n if not hasattr(transform, "transformPoint"):\n transform = Transform(*transform)\n contain_x, contain_y = contain or width is None, contain or height is None\n if contain_x or contain_y:\n dx, dy = transform.dx, transform.dy\n bbox = self.bbox\n p1, p2, p3, p4 = (\n transform.transformPoint((bbox[0], bbox[1])),\n transform.transformPoint((bbox[2], bbox[1])),\n transform.transformPoint((bbox[0], bbox[3])),\n transform.transformPoint((bbox[2], bbox[3])),\n )\n px, py = (p1[0], p2[0], p3[0], p4[0]), (p1[1], p2[1], p3[1], p4[1])\n if contain_x:\n if width is None:\n dx = dx - min(*px)\n width = max(*px) - min(*px)\n else:\n dx = dx - min(min(*px), 0.0)\n width = max(width, max(*px) - min(min(*px), 0.0))\n if contain_y:\n if height is None:\n dy = dy - min(*py)\n height = max(*py) - min(*py)\n else:\n dy = dy - min(min(*py), 0.0)\n height = max(height, max(*py) - min(min(*py), 0.0))\n transform = Transform(*transform[:4], dx, dy)\n width, height = math.ceil(width), math.ceil(height)\n buf = ctypes.create_string_buffer(width * height)\n bitmap = FT_Bitmap(\n (ctypes.c_int)(height),\n (ctypes.c_int)(width),\n (ctypes.c_int)(width),\n (ctypes.POINTER(ctypes.c_ubyte))(buf),\n (ctypes.c_short)(256),\n (ctypes.c_ubyte)(FT_PIXEL_MODE_GRAY),\n (ctypes.c_char)(0),\n (ctypes.c_void_p)(None),\n )\n outline = self.outline(transform=transform, evenOdd=evenOdd)\n err = FT_Outline_Get_Bitmap(\n freetype.get_handle(), ctypes.byref(outline), ctypes.byref(bitmap)\n )\n if err != 0:\n raise FT_Exception(err)\n return buf.raw, (width, height)\n\n def array(\n self, width=None, height=None, transform=None, contain=False, evenOdd=False\n ):\n """Returns the rendered contours as a numpy array. Requires `numpy`.\n\n Args:\n width: Image width of the bitmap in pixels. If omitted, it\n automatically fits to the bounding box of the contours.\n height: Image height of the bitmap in pixels. If omitted, it\n automatically fits to the bounding box of the contours.\n transform: An optional 6-tuple containing an affine transformation,\n or a ``Transform`` object from the ``fontTools.misc.transform``\n module. The bitmap size is not affected by this matrix.\n contain: If ``True``, the image size will be automatically expanded\n so that it fits to the bounding box of the paths. Useful for\n rendering glyphs with negative sidebearings without clipping.\n evenOdd: Pass ``True`` for even-odd fill instead of non-zero.\n\n Returns:\n A ``numpy.ndarray`` object with a shape of ``(height, width)``.\n Each element takes a value in the range of ``[0.0, 1.0]``.\n\n Notes:\n The image size should always be given explicitly if you need to get\n a proper glyph image. When ``width`` and ``height`` are omitted, it\n forcifully fits to the bounding box and the side bearings get\n cropped. If you pass ``0`` to both ``width`` and ``height`` and set\n ``contain`` to ``True``, it expands to the bounding box while\n maintaining the origin of the contours, meaning that LSB will be\n maintained but RSB won’t. The difference between the two becomes\n more obvious when rotate or skew transformation is applied.\n\n Example:\n .. code-block:: pycon\n\n >>>\n >> pen = FreeTypePen(None)\n >> glyph.draw(pen)\n >> arr = pen.array(width=500, height=1000)\n >> type(a), a.shape\n (<class 'numpy.ndarray'>, (1000, 500))\n """\n\n import numpy as np\n\n buf, size = self.buffer(\n width=width,\n height=height,\n transform=transform,\n contain=contain,\n evenOdd=evenOdd,\n )\n return np.frombuffer(buf, "B").reshape((size[1], size[0])) / 255.0\n\n def show(\n self, width=None, height=None, transform=None, contain=False, evenOdd=False\n ):\n """Plots the rendered contours with `pyplot`. Requires `numpy` and\n `matplotlib`.\n\n Args:\n width: Image width of the bitmap in pixels. If omitted, it\n automatically fits to the bounding box of the contours.\n height: Image height of the bitmap in pixels. If omitted, it\n automatically fits to the bounding box of the contours.\n transform: An optional 6-tuple containing an affine transformation,\n or a ``Transform`` object from the ``fontTools.misc.transform``\n module. The bitmap size is not affected by this matrix.\n contain: If ``True``, the image size will be automatically expanded\n so that it fits to the bounding box of the paths. Useful for\n rendering glyphs with negative sidebearings without clipping.\n evenOdd: Pass ``True`` for even-odd fill instead of non-zero.\n\n Notes:\n The image size should always be given explicitly if you need to get\n a proper glyph image. When ``width`` and ``height`` are omitted, it\n forcifully fits to the bounding box and the side bearings get\n cropped. If you pass ``0`` to both ``width`` and ``height`` and set\n ``contain`` to ``True``, it expands to the bounding box while\n maintaining the origin of the contours, meaning that LSB will be\n maintained but RSB won’t. The difference between the two becomes\n more obvious when rotate or skew transformation is applied.\n\n Example:\n .. code-block:: pycon\n\n >>>\n >> pen = FreeTypePen(None)\n >> glyph.draw(pen)\n >> pen.show(width=500, height=1000)\n """\n from matplotlib import pyplot as plt\n\n a = self.array(\n width=width,\n height=height,\n transform=transform,\n contain=contain,\n evenOdd=evenOdd,\n )\n plt.imshow(a, cmap="gray_r", vmin=0, vmax=1)\n plt.show()\n\n def image(\n self, width=None, height=None, transform=None, contain=False, evenOdd=False\n ):\n """Returns the rendered contours as a PIL image. Requires `Pillow`.\n Can be used to display a glyph image in Jupyter Notebook.\n\n Args:\n width: Image width of the bitmap in pixels. If omitted, it\n automatically fits to the bounding box of the contours.\n height: Image height of the bitmap in pixels. If omitted, it\n automatically fits to the bounding box of the contours.\n transform: An optional 6-tuple containing an affine transformation,\n or a ``Transform`` object from the ``fontTools.misc.transform``\n module. The bitmap size is not affected by this matrix.\n contain: If ``True``, the image size will be automatically expanded\n so that it fits to the bounding box of the paths. Useful for\n rendering glyphs with negative sidebearings without clipping.\n evenOdd: Pass ``True`` for even-odd fill instead of non-zero.\n\n Returns:\n A ``PIL.image`` object. The image is filled in black with alpha\n channel obtained from the rendered bitmap.\n\n Notes:\n The image size should always be given explicitly if you need to get\n a proper glyph image. When ``width`` and ``height`` are omitted, it\n forcifully fits to the bounding box and the side bearings get\n cropped. If you pass ``0`` to both ``width`` and ``height`` and set\n ``contain`` to ``True``, it expands to the bounding box while\n maintaining the origin of the contours, meaning that LSB will be\n maintained but RSB won’t. The difference between the two becomes\n more obvious when rotate or skew transformation is applied.\n\n Example:\n .. code-block:: pycon\n\n >>>\n >> pen = FreeTypePen(None)\n >> glyph.draw(pen)\n >> img = pen.image(width=500, height=1000)\n >> type(img), img.size\n (<class 'PIL.Image.Image'>, (500, 1000))\n """\n from PIL import Image\n\n buf, size = self.buffer(\n width=width,\n height=height,\n transform=transform,\n contain=contain,\n evenOdd=evenOdd,\n )\n img = Image.new("L", size, 0)\n img.putalpha(Image.frombuffer("L", size, buf))\n return img\n\n @property\n def bbox(self):\n """Computes the exact bounding box of an outline.\n\n Returns:\n A tuple of ``(xMin, yMin, xMax, yMax)``.\n """\n bbox = FT_BBox()\n outline = self.outline()\n FT_Outline_Get_BBox(ctypes.byref(outline), ctypes.byref(bbox))\n return (bbox.xMin / 64.0, bbox.yMin / 64.0, bbox.xMax / 64.0, bbox.yMax / 64.0)\n\n @property\n def cbox(self):\n """Returns an outline's ‘control box’.\n\n Returns:\n A tuple of ``(xMin, yMin, xMax, yMax)``.\n """\n cbox = FT_BBox()\n outline = self.outline()\n FT_Outline_Get_CBox(ctypes.byref(outline), ctypes.byref(cbox))\n return (cbox.xMin / 64.0, cbox.yMin / 64.0, cbox.xMax / 64.0, cbox.yMax / 64.0)\n\n def _moveTo(self, pt):\n contour = Contour([], [])\n self.contours.append(contour)\n contour.points.append(pt)\n contour.tags.append(FT_CURVE_TAG_ON)\n\n def _lineTo(self, pt):\n if not (self.contours and len(self.contours[-1].points) > 0):\n raise PenError("Contour missing required initial moveTo")\n contour = self.contours[-1]\n contour.points.append(pt)\n contour.tags.append(FT_CURVE_TAG_ON)\n\n def _curveToOne(self, p1, p2, p3):\n if not (self.contours and len(self.contours[-1].points) > 0):\n raise PenError("Contour missing required initial moveTo")\n t1, t2, t3 = FT_CURVE_TAG_CUBIC, FT_CURVE_TAG_CUBIC, FT_CURVE_TAG_ON\n contour = self.contours[-1]\n for p, t in ((p1, t1), (p2, t2), (p3, t3)):\n contour.points.append(p)\n contour.tags.append(t)\n\n def _qCurveToOne(self, p1, p2):\n if not (self.contours and len(self.contours[-1].points) > 0):\n raise PenError("Contour missing required initial moveTo")\n t1, t2 = FT_CURVE_TAG_CONIC, FT_CURVE_TAG_ON\n contour = self.contours[-1]\n for p, t in ((p1, t1), (p2, t2)):\n contour.points.append(p)\n contour.tags.append(t)\n
.venv\Lib\site-packages\fontTools\pens\freetypePen.py
freetypePen.py
Python
20,370
0.95
0.123377
0.002469
python-kit
500
2024-12-04T18:05:36.123621
GPL-3.0
false
e026c1194f2e3dc295865f9ca582fd73
# Modified from https://github.com/adobe-type-tools/psautohint/blob/08b346865710ed3c172f1eb581d6ef243b203f99/python/psautohint/ufoFont.py#L800-L838\nimport hashlib\n\nfrom fontTools.pens.basePen import MissingComponentError\nfrom fontTools.pens.pointPen import AbstractPointPen\n\n\nclass HashPointPen(AbstractPointPen):\n """\n This pen can be used to check if a glyph's contents (outlines plus\n components) have changed.\n\n Components are added as the original outline plus each composite's\n transformation.\n\n Example: You have some TrueType hinting code for a glyph which you want to\n compile. The hinting code specifies a hash value computed with HashPointPen\n that was valid for the glyph's outlines at the time the hinting code was\n written. Now you can calculate the hash for the glyph's current outlines to\n check if the outlines have changed, which would probably make the hinting\n code invalid.\n\n > glyph = ufo[name]\n > hash_pen = HashPointPen(glyph.width, ufo)\n > glyph.drawPoints(hash_pen)\n > ttdata = glyph.lib.get("public.truetype.instructions", None)\n > stored_hash = ttdata.get("id", None) # The hash is stored in the "id" key\n > if stored_hash is None or stored_hash != hash_pen.hash:\n > logger.error(f"Glyph hash mismatch, glyph '{name}' will have no instructions in font.")\n > else:\n > # The hash values are identical, the outline has not changed.\n > # Compile the hinting code ...\n > pass\n\n If you want to compare a glyph from a source format which supports floating point\n coordinates and transformations against a glyph from a format which has restrictions\n on the precision of floats, e.g. UFO vs. TTF, you must use an appropriate rounding\n function to make the values comparable. For TTF fonts with composites, this\n construct can be used to make the transform values conform to F2Dot14:\n\n > ttf_hash_pen = HashPointPen(ttf_glyph_width, ttFont.getGlyphSet())\n > ttf_round_pen = RoundingPointPen(ttf_hash_pen, transformRoundFunc=partial(floatToFixedToFloat, precisionBits=14))\n > ufo_hash_pen = HashPointPen(ufo_glyph.width, ufo)\n > ttf_glyph.drawPoints(ttf_round_pen, ttFont["glyf"])\n > ufo_round_pen = RoundingPointPen(ufo_hash_pen, transformRoundFunc=partial(floatToFixedToFloat, precisionBits=14))\n > ufo_glyph.drawPoints(ufo_round_pen)\n > assert ttf_hash_pen.hash == ufo_hash_pen.hash\n """\n\n def __init__(self, glyphWidth=0, glyphSet=None):\n self.glyphset = glyphSet\n self.data = ["w%s" % round(glyphWidth, 9)]\n\n @property\n def hash(self):\n data = "".join(self.data)\n if len(data) >= 128:\n data = hashlib.sha512(data.encode("ascii")).hexdigest()\n return data\n\n def beginPath(self, identifier=None, **kwargs):\n pass\n\n def endPath(self):\n self.data.append("|")\n\n def addPoint(\n self,\n pt,\n segmentType=None,\n smooth=False,\n name=None,\n identifier=None,\n **kwargs,\n ):\n if segmentType is None:\n pt_type = "o" # offcurve\n else:\n pt_type = segmentType[0]\n self.data.append(f"{pt_type}{pt[0]:g}{pt[1]:+g}")\n\n def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):\n tr = "".join([f"{t:+}" for t in transformation])\n self.data.append("[")\n try:\n self.glyphset[baseGlyphName].drawPoints(self)\n except KeyError:\n raise MissingComponentError(baseGlyphName)\n self.data.append(f"({tr})]")\n
.venv\Lib\site-packages\fontTools\pens\hashPointPen.py
hashPointPen.py
Python
3,662
0.95
0.202247
0.026667
react-lib
736
2025-04-10T14:01:52.266484
BSD-3-Clause
false
1fb4b513fee11b74d0620961c18e5271
MZ
.venv\Lib\site-packages\fontTools\pens\momentsPen.cp313-win_amd64.pyd
momentsPen.cp313-win_amd64.pyd
Other
89,088
0.75
0.017212
0.00346
react-lib
357
2024-11-13T19:15:28.411744
BSD-3-Clause
false
3bc730023895d5f26062f61f6102da2e
from fontTools.pens.basePen import BasePen, OpenContourError\n\ntry:\n import cython\nexcept (AttributeError, ImportError):\n # if cython not installed, use mock module with no-op decorators and types\n from fontTools.misc import cython\nCOMPILED = cython.compiled\n\n\n__all__ = ["MomentsPen"]\n\n\nclass MomentsPen(BasePen):\n\n def __init__(self, glyphset=None):\n BasePen.__init__(self, glyphset)\n\n self.area = 0\n self.momentX = 0\n self.momentY = 0\n self.momentXX = 0\n self.momentXY = 0\n self.momentYY = 0\n\n def _moveTo(self, p0):\n self._startPoint = p0\n\n def _closePath(self):\n p0 = self._getCurrentPoint()\n if p0 != self._startPoint:\n self._lineTo(self._startPoint)\n\n def _endPath(self):\n p0 = self._getCurrentPoint()\n if p0 != self._startPoint:\n raise OpenContourError("Glyph statistics is not defined on open contours.")\n\n @cython.locals(r0=cython.double)\n @cython.locals(r1=cython.double)\n @cython.locals(r2=cython.double)\n @cython.locals(r3=cython.double)\n @cython.locals(r4=cython.double)\n @cython.locals(r5=cython.double)\n @cython.locals(r6=cython.double)\n @cython.locals(r7=cython.double)\n @cython.locals(r8=cython.double)\n @cython.locals(r9=cython.double)\n @cython.locals(r10=cython.double)\n @cython.locals(r11=cython.double)\n @cython.locals(r12=cython.double)\n @cython.locals(x0=cython.double, y0=cython.double)\n @cython.locals(x1=cython.double, y1=cython.double)\n def _lineTo(self, p1):\n x0, y0 = self._getCurrentPoint()\n x1, y1 = p1\n\n r0 = x1 * y0\n r1 = x1 * y1\n r2 = x1**2\n r3 = r2 * y1\n r4 = y0 - y1\n r5 = r4 * x0\n r6 = x0**2\n r7 = 2 * y0\n r8 = y0**2\n r9 = y1**2\n r10 = x1**3\n r11 = y0**3\n r12 = y1**3\n\n self.area += -r0 / 2 - r1 / 2 + x0 * (y0 + y1) / 2\n self.momentX += -r2 * y0 / 6 - r3 / 3 - r5 * x1 / 6 + r6 * (r7 + y1) / 6\n self.momentY += (\n -r0 * y1 / 6 - r8 * x1 / 6 - r9 * x1 / 6 + x0 * (r8 + r9 + y0 * y1) / 6\n )\n self.momentXX += (\n -r10 * y0 / 12\n - r10 * y1 / 4\n - r2 * r5 / 12\n - r4 * r6 * x1 / 12\n + x0**3 * (3 * y0 + y1) / 12\n )\n self.momentXY += (\n -r2 * r8 / 24\n - r2 * r9 / 8\n - r3 * r7 / 24\n + r6 * (r7 * y1 + 3 * r8 + r9) / 24\n - x0 * x1 * (r8 - r9) / 12\n )\n self.momentYY += (\n -r0 * r9 / 12\n - r1 * r8 / 12\n - r11 * x1 / 12\n - r12 * x1 / 12\n + x0 * (r11 + r12 + r8 * y1 + r9 * y0) / 12\n )\n\n @cython.locals(r0=cython.double)\n @cython.locals(r1=cython.double)\n @cython.locals(r2=cython.double)\n @cython.locals(r3=cython.double)\n @cython.locals(r4=cython.double)\n @cython.locals(r5=cython.double)\n @cython.locals(r6=cython.double)\n @cython.locals(r7=cython.double)\n @cython.locals(r8=cython.double)\n @cython.locals(r9=cython.double)\n @cython.locals(r10=cython.double)\n @cython.locals(r11=cython.double)\n @cython.locals(r12=cython.double)\n @cython.locals(r13=cython.double)\n @cython.locals(r14=cython.double)\n @cython.locals(r15=cython.double)\n @cython.locals(r16=cython.double)\n @cython.locals(r17=cython.double)\n @cython.locals(r18=cython.double)\n @cython.locals(r19=cython.double)\n @cython.locals(r20=cython.double)\n @cython.locals(r21=cython.double)\n @cython.locals(r22=cython.double)\n @cython.locals(r23=cython.double)\n @cython.locals(r24=cython.double)\n @cython.locals(r25=cython.double)\n @cython.locals(r26=cython.double)\n @cython.locals(r27=cython.double)\n @cython.locals(r28=cython.double)\n @cython.locals(r29=cython.double)\n @cython.locals(r30=cython.double)\n @cython.locals(r31=cython.double)\n @cython.locals(r32=cython.double)\n @cython.locals(r33=cython.double)\n @cython.locals(r34=cython.double)\n @cython.locals(r35=cython.double)\n @cython.locals(r36=cython.double)\n @cython.locals(r37=cython.double)\n @cython.locals(r38=cython.double)\n @cython.locals(r39=cython.double)\n @cython.locals(r40=cython.double)\n @cython.locals(r41=cython.double)\n @cython.locals(r42=cython.double)\n @cython.locals(r43=cython.double)\n @cython.locals(r44=cython.double)\n @cython.locals(r45=cython.double)\n @cython.locals(r46=cython.double)\n @cython.locals(r47=cython.double)\n @cython.locals(r48=cython.double)\n @cython.locals(r49=cython.double)\n @cython.locals(r50=cython.double)\n @cython.locals(r51=cython.double)\n @cython.locals(r52=cython.double)\n @cython.locals(r53=cython.double)\n @cython.locals(x0=cython.double, y0=cython.double)\n @cython.locals(x1=cython.double, y1=cython.double)\n @cython.locals(x2=cython.double, y2=cython.double)\n def _qCurveToOne(self, p1, p2):\n x0, y0 = self._getCurrentPoint()\n x1, y1 = p1\n x2, y2 = p2\n\n r0 = 2 * y1\n r1 = r0 * x2\n r2 = x2 * y2\n r3 = 3 * r2\n r4 = 2 * x1\n r5 = 3 * y0\n r6 = x1**2\n r7 = x2**2\n r8 = 4 * y1\n r9 = 10 * y2\n r10 = 2 * y2\n r11 = r4 * x2\n r12 = x0**2\n r13 = 10 * y0\n r14 = r4 * y2\n r15 = x2 * y0\n r16 = 4 * x1\n r17 = r0 * x1 + r2\n r18 = r2 * r8\n r19 = y1**2\n r20 = 2 * r19\n r21 = y2**2\n r22 = r21 * x2\n r23 = 5 * r22\n r24 = y0**2\n r25 = y0 * y2\n r26 = 5 * r24\n r27 = x1**3\n r28 = x2**3\n r29 = 30 * y1\n r30 = 6 * y1\n r31 = 10 * r7 * x1\n r32 = 5 * y2\n r33 = 12 * r6\n r34 = 30 * x1\n r35 = x1 * y1\n r36 = r3 + 20 * r35\n r37 = 12 * x1\n r38 = 20 * r6\n r39 = 8 * r6 * y1\n r40 = r32 * r7\n r41 = 60 * y1\n r42 = 20 * r19\n r43 = 4 * r19\n r44 = 15 * r21\n r45 = 12 * x2\n r46 = 12 * y2\n r47 = 6 * x1\n r48 = 8 * r19 * x1 + r23\n r49 = 8 * y1**3\n r50 = y2**3\n r51 = y0**3\n r52 = 10 * y1\n r53 = 12 * y1\n\n self.area += (\n -r1 / 6\n - r3 / 6\n + x0 * (r0 + r5 + y2) / 6\n + x1 * y2 / 3\n - y0 * (r4 + x2) / 6\n )\n self.momentX += (\n -r11 * (-r10 + y1) / 30\n + r12 * (r13 + r8 + y2) / 30\n + r6 * y2 / 15\n - r7 * r8 / 30\n - r7 * r9 / 30\n + x0 * (r14 - r15 - r16 * y0 + r17) / 30\n - y0 * (r11 + 2 * r6 + r7) / 30\n )\n self.momentY += (\n -r18 / 30\n - r20 * x2 / 30\n - r23 / 30\n - r24 * (r16 + x2) / 30\n + x0 * (r0 * y2 + r20 + r21 + r25 + r26 + r8 * y0) / 30\n + x1 * y2 * (r10 + y1) / 15\n - y0 * (r1 + r17) / 30\n )\n self.momentXX += (\n r12 * (r1 - 5 * r15 - r34 * y0 + r36 + r9 * x1) / 420\n + 2 * r27 * y2 / 105\n - r28 * r29 / 420\n - r28 * y2 / 4\n - r31 * (r0 - 3 * y2) / 420\n - r6 * x2 * (r0 - r32) / 105\n + x0**3 * (r30 + 21 * y0 + y2) / 84\n - x0\n * (\n r0 * r7\n + r15 * r37\n - r2 * r37\n - r33 * y2\n + r38 * y0\n - r39\n - r40\n + r5 * r7\n )\n / 420\n - y0 * (8 * r27 + 5 * r28 + r31 + r33 * x2) / 420\n )\n self.momentXY += (\n r12 * (r13 * y2 + 3 * r21 + 105 * r24 + r41 * y0 + r42 + r46 * y1) / 840\n - r16 * x2 * (r43 - r44) / 840\n - r21 * r7 / 8\n - r24 * (r38 + r45 * x1 + 3 * r7) / 840\n - r41 * r7 * y2 / 840\n - r42 * r7 / 840\n + r6 * y2 * (r32 + r8) / 210\n + x0\n * (\n -r15 * r8\n + r16 * r25\n + r18\n + r21 * r47\n - r24 * r34\n - r26 * x2\n + r35 * r46\n + r48\n )\n / 420\n - y0 * (r16 * r2 + r30 * r7 + r35 * r45 + r39 + r40) / 420\n )\n self.momentYY += (\n -r2 * r42 / 420\n - r22 * r29 / 420\n - r24 * (r14 + r36 + r52 * x2) / 420\n - r49 * x2 / 420\n - r50 * x2 / 12\n - r51 * (r47 + x2) / 84\n + x0\n * (\n r19 * r46\n + r21 * r5\n + r21 * r52\n + r24 * r29\n + r25 * r53\n + r26 * y2\n + r42 * y0\n + r49\n + 5 * r50\n + 35 * r51\n )\n / 420\n + x1 * y2 * (r43 + r44 + r9 * y1) / 210\n - y0 * (r19 * r45 + r2 * r53 - r21 * r4 + r48) / 420\n )\n\n @cython.locals(r0=cython.double)\n @cython.locals(r1=cython.double)\n @cython.locals(r2=cython.double)\n @cython.locals(r3=cython.double)\n @cython.locals(r4=cython.double)\n @cython.locals(r5=cython.double)\n @cython.locals(r6=cython.double)\n @cython.locals(r7=cython.double)\n @cython.locals(r8=cython.double)\n @cython.locals(r9=cython.double)\n @cython.locals(r10=cython.double)\n @cython.locals(r11=cython.double)\n @cython.locals(r12=cython.double)\n @cython.locals(r13=cython.double)\n @cython.locals(r14=cython.double)\n @cython.locals(r15=cython.double)\n @cython.locals(r16=cython.double)\n @cython.locals(r17=cython.double)\n @cython.locals(r18=cython.double)\n @cython.locals(r19=cython.double)\n @cython.locals(r20=cython.double)\n @cython.locals(r21=cython.double)\n @cython.locals(r22=cython.double)\n @cython.locals(r23=cython.double)\n @cython.locals(r24=cython.double)\n @cython.locals(r25=cython.double)\n @cython.locals(r26=cython.double)\n @cython.locals(r27=cython.double)\n @cython.locals(r28=cython.double)\n @cython.locals(r29=cython.double)\n @cython.locals(r30=cython.double)\n @cython.locals(r31=cython.double)\n @cython.locals(r32=cython.double)\n @cython.locals(r33=cython.double)\n @cython.locals(r34=cython.double)\n @cython.locals(r35=cython.double)\n @cython.locals(r36=cython.double)\n @cython.locals(r37=cython.double)\n @cython.locals(r38=cython.double)\n @cython.locals(r39=cython.double)\n @cython.locals(r40=cython.double)\n @cython.locals(r41=cython.double)\n @cython.locals(r42=cython.double)\n @cython.locals(r43=cython.double)\n @cython.locals(r44=cython.double)\n @cython.locals(r45=cython.double)\n @cython.locals(r46=cython.double)\n @cython.locals(r47=cython.double)\n @cython.locals(r48=cython.double)\n @cython.locals(r49=cython.double)\n @cython.locals(r50=cython.double)\n @cython.locals(r51=cython.double)\n @cython.locals(r52=cython.double)\n @cython.locals(r53=cython.double)\n @cython.locals(r54=cython.double)\n @cython.locals(r55=cython.double)\n @cython.locals(r56=cython.double)\n @cython.locals(r57=cython.double)\n @cython.locals(r58=cython.double)\n @cython.locals(r59=cython.double)\n @cython.locals(r60=cython.double)\n @cython.locals(r61=cython.double)\n @cython.locals(r62=cython.double)\n @cython.locals(r63=cython.double)\n @cython.locals(r64=cython.double)\n @cython.locals(r65=cython.double)\n @cython.locals(r66=cython.double)\n @cython.locals(r67=cython.double)\n @cython.locals(r68=cython.double)\n @cython.locals(r69=cython.double)\n @cython.locals(r70=cython.double)\n @cython.locals(r71=cython.double)\n @cython.locals(r72=cython.double)\n @cython.locals(r73=cython.double)\n @cython.locals(r74=cython.double)\n @cython.locals(r75=cython.double)\n @cython.locals(r76=cython.double)\n @cython.locals(r77=cython.double)\n @cython.locals(r78=cython.double)\n @cython.locals(r79=cython.double)\n @cython.locals(r80=cython.double)\n @cython.locals(r81=cython.double)\n @cython.locals(r82=cython.double)\n @cython.locals(r83=cython.double)\n @cython.locals(r84=cython.double)\n @cython.locals(r85=cython.double)\n @cython.locals(r86=cython.double)\n @cython.locals(r87=cython.double)\n @cython.locals(r88=cython.double)\n @cython.locals(r89=cython.double)\n @cython.locals(r90=cython.double)\n @cython.locals(r91=cython.double)\n @cython.locals(r92=cython.double)\n @cython.locals(r93=cython.double)\n @cython.locals(r94=cython.double)\n @cython.locals(r95=cython.double)\n @cython.locals(r96=cython.double)\n @cython.locals(r97=cython.double)\n @cython.locals(r98=cython.double)\n @cython.locals(r99=cython.double)\n @cython.locals(r100=cython.double)\n @cython.locals(r101=cython.double)\n @cython.locals(r102=cython.double)\n @cython.locals(r103=cython.double)\n @cython.locals(r104=cython.double)\n @cython.locals(r105=cython.double)\n @cython.locals(r106=cython.double)\n @cython.locals(r107=cython.double)\n @cython.locals(r108=cython.double)\n @cython.locals(r109=cython.double)\n @cython.locals(r110=cython.double)\n @cython.locals(r111=cython.double)\n @cython.locals(r112=cython.double)\n @cython.locals(r113=cython.double)\n @cython.locals(r114=cython.double)\n @cython.locals(r115=cython.double)\n @cython.locals(r116=cython.double)\n @cython.locals(r117=cython.double)\n @cython.locals(r118=cython.double)\n @cython.locals(r119=cython.double)\n @cython.locals(r120=cython.double)\n @cython.locals(r121=cython.double)\n @cython.locals(r122=cython.double)\n @cython.locals(r123=cython.double)\n @cython.locals(r124=cython.double)\n @cython.locals(r125=cython.double)\n @cython.locals(r126=cython.double)\n @cython.locals(r127=cython.double)\n @cython.locals(r128=cython.double)\n @cython.locals(r129=cython.double)\n @cython.locals(r130=cython.double)\n @cython.locals(r131=cython.double)\n @cython.locals(r132=cython.double)\n @cython.locals(x0=cython.double, y0=cython.double)\n @cython.locals(x1=cython.double, y1=cython.double)\n @cython.locals(x2=cython.double, y2=cython.double)\n @cython.locals(x3=cython.double, y3=cython.double)\n def _curveToOne(self, p1, p2, p3):\n x0, y0 = self._getCurrentPoint()\n x1, y1 = p1\n x2, y2 = p2\n x3, y3 = p3\n\n r0 = 6 * y2\n r1 = r0 * x3\n r2 = 10 * y3\n r3 = r2 * x3\n r4 = 3 * y1\n r5 = 6 * x1\n r6 = 3 * x2\n r7 = 6 * y1\n r8 = 3 * y2\n r9 = x2**2\n r10 = 45 * r9\n r11 = r10 * y3\n r12 = x3**2\n r13 = r12 * y2\n r14 = r12 * y3\n r15 = 7 * y3\n r16 = 15 * x3\n r17 = r16 * x2\n r18 = x1**2\n r19 = 9 * r18\n r20 = x0**2\n r21 = 21 * y1\n r22 = 9 * r9\n r23 = r7 * x3\n r24 = 9 * y2\n r25 = r24 * x2 + r3\n r26 = 9 * x2\n r27 = x2 * y3\n r28 = -r26 * y1 + 15 * r27\n r29 = 3 * x1\n r30 = 45 * x1\n r31 = 12 * x3\n r32 = 45 * r18\n r33 = 5 * r12\n r34 = r8 * x3\n r35 = 105 * y0\n r36 = 30 * y0\n r37 = r36 * x2\n r38 = 5 * x3\n r39 = 15 * y3\n r40 = 5 * y3\n r41 = r40 * x3\n r42 = x2 * y2\n r43 = 18 * r42\n r44 = 45 * y1\n r45 = r41 + r43 + r44 * x1\n r46 = y2 * y3\n r47 = r46 * x3\n r48 = y2**2\n r49 = 45 * r48\n r50 = r49 * x3\n r51 = y3**2\n r52 = r51 * x3\n r53 = y1**2\n r54 = 9 * r53\n r55 = y0**2\n r56 = 21 * x1\n r57 = 6 * x2\n r58 = r16 * y2\n r59 = r39 * y2\n r60 = 9 * r48\n r61 = r6 * y3\n r62 = 3 * y3\n r63 = r36 * y2\n r64 = y1 * y3\n r65 = 45 * r53\n r66 = 5 * r51\n r67 = x2**3\n r68 = x3**3\n r69 = 630 * y2\n r70 = 126 * x3\n r71 = x1**3\n r72 = 126 * x2\n r73 = 63 * r9\n r74 = r73 * x3\n r75 = r15 * x3 + 15 * r42\n r76 = 630 * x1\n r77 = 14 * x3\n r78 = 21 * r27\n r79 = 42 * x1\n r80 = 42 * x2\n r81 = x1 * y2\n r82 = 63 * r42\n r83 = x1 * y1\n r84 = r41 + r82 + 378 * r83\n r85 = x2 * x3\n r86 = r85 * y1\n r87 = r27 * x3\n r88 = 27 * r9\n r89 = r88 * y2\n r90 = 42 * r14\n r91 = 90 * x1\n r92 = 189 * r18\n r93 = 378 * r18\n r94 = r12 * y1\n r95 = 252 * x1 * x2\n r96 = r79 * x3\n r97 = 30 * r85\n r98 = r83 * x3\n r99 = 30 * x3\n r100 = 42 * x3\n r101 = r42 * x1\n r102 = r10 * y2 + 14 * r14 + 126 * r18 * y1 + r81 * r99\n r103 = 378 * r48\n r104 = 18 * y1\n r105 = r104 * y2\n r106 = y0 * y1\n r107 = 252 * y2\n r108 = r107 * y0\n r109 = y0 * y3\n r110 = 42 * r64\n r111 = 378 * r53\n r112 = 63 * r48\n r113 = 27 * x2\n r114 = r27 * y2\n r115 = r113 * r48 + 42 * r52\n r116 = x3 * y3\n r117 = 54 * r42\n r118 = r51 * x1\n r119 = r51 * x2\n r120 = r48 * x1\n r121 = 21 * x3\n r122 = r64 * x1\n r123 = r81 * y3\n r124 = 30 * r27 * y1 + r49 * x2 + 14 * r52 + 126 * r53 * x1\n r125 = y2**3\n r126 = y3**3\n r127 = y1**3\n r128 = y0**3\n r129 = r51 * y2\n r130 = r112 * y3 + r21 * r51\n r131 = 189 * r53\n r132 = 90 * y2\n\n self.area += (\n -r1 / 20\n - r3 / 20\n - r4 * (x2 + x3) / 20\n + x0 * (r7 + r8 + 10 * y0 + y3) / 20\n + 3 * x1 * (y2 + y3) / 20\n + 3 * x2 * y3 / 10\n - y0 * (r5 + r6 + x3) / 20\n )\n self.momentX += (\n r11 / 840\n - r13 / 8\n - r14 / 3\n - r17 * (-r15 + r8) / 840\n + r19 * (r8 + 2 * y3) / 840\n + r20 * (r0 + r21 + 56 * y0 + y3) / 168\n + r29 * (-r23 + r25 + r28) / 840\n - r4 * (10 * r12 + r17 + r22) / 840\n + x0\n * (\n 12 * r27\n + r30 * y2\n + r34\n - r35 * x1\n - r37\n - r38 * y0\n + r39 * x1\n - r4 * x3\n + r45\n )\n / 840\n - y0 * (r17 + r30 * x2 + r31 * x1 + r32 + r33 + 18 * r9) / 840\n )\n self.momentY += (\n -r4 * (r25 + r58) / 840\n - r47 / 8\n - r50 / 840\n - r52 / 6\n - r54 * (r6 + 2 * x3) / 840\n - r55 * (r56 + r57 + x3) / 168\n + x0\n * (\n r35 * y1\n + r40 * y0\n + r44 * y2\n + 18 * r48\n + 140 * r55\n + r59\n + r63\n + 12 * r64\n + r65\n + r66\n )\n / 840\n + x1 * (r24 * y1 + 10 * r51 + r59 + r60 + r7 * y3) / 280\n + x2 * y3 * (r15 + r8) / 56\n - y0 * (r16 * y1 + r31 * y2 + r44 * x2 + r45 + r61 - r62 * x1) / 840\n )\n self.momentXX += (\n -r12 * r72 * (-r40 + r8) / 9240\n + 3 * r18 * (r28 + r34 - r38 * y1 + r75) / 3080\n + r20\n * (\n r24 * x3\n - r72 * y0\n - r76 * y0\n - r77 * y0\n + r78\n + r79 * y3\n + r80 * y1\n + 210 * r81\n + r84\n )\n / 9240\n - r29\n * (\n r12 * r21\n + 14 * r13\n + r44 * r9\n - r73 * y3\n + 54 * r86\n - 84 * r87\n - r89\n - r90\n )\n / 9240\n - r4 * (70 * r12 * x2 + 27 * r67 + 42 * r68 + r74) / 9240\n + 3 * r67 * y3 / 220\n - r68 * r69 / 9240\n - r68 * y3 / 4\n - r70 * r9 * (-r62 + y2) / 9240\n + 3 * r71 * (r24 + r40) / 3080\n + x0**3 * (r24 + r44 + 165 * y0 + y3) / 660\n + x0\n * (\n r100 * r27\n + 162 * r101\n + r102\n + r11\n + 63 * r18 * y3\n + r27 * r91\n - r33 * y0\n - r37 * x3\n + r43 * x3\n - r73 * y0\n - r88 * y1\n + r92 * y2\n - r93 * y0\n - 9 * r94\n - r95 * y0\n - r96 * y0\n - r97 * y1\n - 18 * r98\n + r99 * x1 * y3\n )\n / 9240\n - y0\n * (\n r12 * r56\n + r12 * r80\n + r32 * x3\n + 45 * r67\n + 14 * r68\n + 126 * r71\n + r74\n + r85 * r91\n + 135 * r9 * x1\n + r92 * x2\n )\n / 9240\n )\n self.momentXY += (\n -r103 * r12 / 18480\n - r12 * r51 / 8\n - 3 * r14 * y2 / 44\n + 3 * r18 * (r105 + r2 * y1 + 18 * r46 + 15 * r48 + 7 * r51) / 6160\n + r20\n * (\n 1260 * r106\n + r107 * y1\n + r108\n + 28 * r109\n + r110\n + r111\n + r112\n + 30 * r46\n + 2310 * r55\n + r66\n )\n / 18480\n - r54 * (7 * r12 + 18 * r85 + 15 * r9) / 18480\n - r55 * (r33 + r73 + r93 + r95 + r96 + r97) / 18480\n - r7 * (42 * r13 + r82 * x3 + 28 * r87 + r89 + r90) / 18480\n - 3 * r85 * (r48 - r66) / 220\n + 3 * r9 * y3 * (r62 + 2 * y2) / 440\n + x0\n * (\n -r1 * y0\n - 84 * r106 * x2\n + r109 * r56\n + 54 * r114\n + r117 * y1\n + 15 * r118\n + 21 * r119\n + 81 * r120\n + r121 * r46\n + 54 * r122\n + 60 * r123\n + r124\n - r21 * x3 * y0\n + r23 * y3\n - r54 * x3\n - r55 * r72\n - r55 * r76\n - r55 * r77\n + r57 * y0 * y3\n + r60 * x3\n + 84 * r81 * y0\n + 189 * r81 * y1\n )\n / 9240\n + x1\n * (\n r104 * r27\n - r105 * x3\n - r113 * r53\n + 63 * r114\n + r115\n - r16 * r53\n + 28 * r47\n + r51 * r80\n )\n / 3080\n - y0\n * (\n 54 * r101\n + r102\n + r116 * r5\n + r117 * x3\n + 21 * r13\n - r19 * y3\n + r22 * y3\n + r78 * x3\n + 189 * r83 * x2\n + 60 * r86\n + 81 * r9 * y1\n + 15 * r94\n + 54 * r98\n )\n / 9240\n )\n self.momentYY += (\n -r103 * r116 / 9240\n - r125 * r70 / 9240\n - r126 * x3 / 12\n - 3 * r127 * (r26 + r38) / 3080\n - r128 * (r26 + r30 + x3) / 660\n - r4 * (r112 * x3 + r115 - 14 * r119 + 84 * r47) / 9240\n - r52 * r69 / 9240\n - r54 * (r58 + r61 + r75) / 9240\n - r55\n * (r100 * y1 + r121 * y2 + r26 * y3 + r79 * y2 + r84 + 210 * x2 * y1)\n / 9240\n + x0\n * (\n r108 * y1\n + r110 * y0\n + r111 * y0\n + r112 * y0\n + 45 * r125\n + 14 * r126\n + 126 * r127\n + 770 * r128\n + 42 * r129\n + r130\n + r131 * y2\n + r132 * r64\n + 135 * r48 * y1\n + 630 * r55 * y1\n + 126 * r55 * y2\n + 14 * r55 * y3\n + r63 * y3\n + r65 * y3\n + r66 * y0\n )\n / 9240\n + x1\n * (\n 27 * r125\n + 42 * r126\n + 70 * r129\n + r130\n + r39 * r53\n + r44 * r48\n + 27 * r53 * y2\n + 54 * r64 * y2\n )\n / 3080\n + 3 * x2 * y3 * (r48 + r66 + r8 * y3) / 220\n - y0\n * (\n r100 * r46\n + 18 * r114\n - 9 * r118\n - 27 * r120\n - 18 * r122\n - 30 * r123\n + r124\n + r131 * x2\n + r132 * x3 * y1\n + 162 * r42 * y1\n + r50\n + 63 * r53 * x3\n + r64 * r99\n )\n / 9240\n )\n\n\nif __name__ == "__main__":\n from fontTools.misc.symfont import x, y, printGreenPen\n\n printGreenPen(\n "MomentsPen",\n [\n ("area", 1),\n ("momentX", x),\n ("momentY", y),\n ("momentXX", x**2),\n ("momentXY", x * y),\n ("momentYY", y**2),\n ],\n )\n
.venv\Lib\site-packages\fontTools\pens\momentsPen.py
momentsPen.py
Python
26,537
0.95
0.01479
0.021004
vue-tools
297
2024-12-18T20:38:45.772581
Apache-2.0
false
581ab99848786a07bc41f39ee9e91222
# -*- coding: utf-8 -*-\n"""Calculate the perimeter of a glyph."""\n\nfrom fontTools.pens.basePen import BasePen\nfrom fontTools.misc.bezierTools import (\n approximateQuadraticArcLengthC,\n calcQuadraticArcLengthC,\n approximateCubicArcLengthC,\n calcCubicArcLengthC,\n)\nimport math\n\n\n__all__ = ["PerimeterPen"]\n\n\ndef _distance(p0, p1):\n return math.hypot(p0[0] - p1[0], p0[1] - p1[1])\n\n\nclass PerimeterPen(BasePen):\n def __init__(self, glyphset=None, tolerance=0.005):\n BasePen.__init__(self, glyphset)\n self.value = 0\n self.tolerance = tolerance\n\n # Choose which algorithm to use for quadratic and for cubic.\n # Quadrature is faster but has fixed error characteristic with no strong\n # error bound. The cutoff points are derived empirically.\n self._addCubic = (\n self._addCubicQuadrature if tolerance >= 0.0015 else self._addCubicRecursive\n )\n self._addQuadratic = (\n self._addQuadraticQuadrature\n if tolerance >= 0.00075\n else self._addQuadraticExact\n )\n\n def _moveTo(self, p0):\n self.__startPoint = p0\n\n def _closePath(self):\n p0 = self._getCurrentPoint()\n if p0 != self.__startPoint:\n self._lineTo(self.__startPoint)\n\n def _lineTo(self, p1):\n p0 = self._getCurrentPoint()\n self.value += _distance(p0, p1)\n\n def _addQuadraticExact(self, c0, c1, c2):\n self.value += calcQuadraticArcLengthC(c0, c1, c2)\n\n def _addQuadraticQuadrature(self, c0, c1, c2):\n self.value += approximateQuadraticArcLengthC(c0, c1, c2)\n\n def _qCurveToOne(self, p1, p2):\n p0 = self._getCurrentPoint()\n self._addQuadratic(complex(*p0), complex(*p1), complex(*p2))\n\n def _addCubicRecursive(self, c0, c1, c2, c3):\n self.value += calcCubicArcLengthC(c0, c1, c2, c3, self.tolerance)\n\n def _addCubicQuadrature(self, c0, c1, c2, c3):\n self.value += approximateCubicArcLengthC(c0, c1, c2, c3)\n\n def _curveToOne(self, p1, p2, p3):\n p0 = self._getCurrentPoint()\n self._addCubic(complex(*p0), complex(*p1), complex(*p2), complex(*p3))\n
.venv\Lib\site-packages\fontTools\pens\perimeterPen.py
perimeterPen.py
Python
2,222
0.95
0.246377
0.076923
react-lib
16
2025-01-19T20:02:54.556000
GPL-3.0
false
bae56890e607cd0973e294560a0fcf25
"""fontTools.pens.pointInsidePen -- Pen implementing "point inside" testing\nfor shapes.\n"""\n\nfrom fontTools.pens.basePen import BasePen\nfrom fontTools.misc.bezierTools import solveQuadratic, solveCubic\n\n\n__all__ = ["PointInsidePen"]\n\n\nclass PointInsidePen(BasePen):\n """This pen implements "point inside" testing: to test whether\n a given point lies inside the shape (black) or outside (white).\n Instances of this class can be recycled, as long as the\n setTestPoint() method is used to set the new point to test.\n\n :Example:\n .. code-block::\n\n pen = PointInsidePen(glyphSet, (100, 200))\n outline.draw(pen)\n isInside = pen.getResult()\n\n Both the even-odd algorithm and the non-zero-winding-rule\n algorithm are implemented. The latter is the default, specify\n True for the evenOdd argument of __init__ or setTestPoint\n to use the even-odd algorithm.\n """\n\n # This class implements the classical "shoot a ray from the test point\n # to infinity and count how many times it intersects the outline" (as well\n # as the non-zero variant, where the counter is incremented if the outline\n # intersects the ray in one direction and decremented if it intersects in\n # the other direction).\n # I found an amazingly clear explanation of the subtleties involved in\n # implementing this correctly for polygons here:\n # http://graphics.cs.ucdavis.edu/~okreylos/TAship/Spring2000/PointInPolygon.html\n # I extended the principles outlined on that page to curves.\n\n def __init__(self, glyphSet, testPoint, evenOdd=False):\n BasePen.__init__(self, glyphSet)\n self.setTestPoint(testPoint, evenOdd)\n\n def setTestPoint(self, testPoint, evenOdd=False):\n """Set the point to test. Call this _before_ the outline gets drawn."""\n self.testPoint = testPoint\n self.evenOdd = evenOdd\n self.firstPoint = None\n self.intersectionCount = 0\n\n def getWinding(self):\n if self.firstPoint is not None:\n # always make sure the sub paths are closed; the algorithm only works\n # for closed paths.\n self.closePath()\n return self.intersectionCount\n\n def getResult(self):\n """After the shape has been drawn, getResult() returns True if the test\n point lies within the (black) shape, and False if it doesn't.\n """\n winding = self.getWinding()\n if self.evenOdd:\n result = winding % 2\n else: # non-zero\n result = self.intersectionCount != 0\n return not not result\n\n def _addIntersection(self, goingUp):\n if self.evenOdd or goingUp:\n self.intersectionCount += 1\n else:\n self.intersectionCount -= 1\n\n def _moveTo(self, point):\n if self.firstPoint is not None:\n # always make sure the sub paths are closed; the algorithm only works\n # for closed paths.\n self.closePath()\n self.firstPoint = point\n\n def _lineTo(self, point):\n x, y = self.testPoint\n x1, y1 = self._getCurrentPoint()\n x2, y2 = point\n\n if x1 < x and x2 < x:\n return\n if y1 < y and y2 < y:\n return\n if y1 >= y and y2 >= y:\n return\n\n dx = x2 - x1\n dy = y2 - y1\n t = (y - y1) / dy\n ix = dx * t + x1\n if ix < x:\n return\n self._addIntersection(y2 > y1)\n\n def _curveToOne(self, bcp1, bcp2, point):\n x, y = self.testPoint\n x1, y1 = self._getCurrentPoint()\n x2, y2 = bcp1\n x3, y3 = bcp2\n x4, y4 = point\n\n if x1 < x and x2 < x and x3 < x and x4 < x:\n return\n if y1 < y and y2 < y and y3 < y and y4 < y:\n return\n if y1 >= y and y2 >= y and y3 >= y and y4 >= y:\n return\n\n dy = y1\n cy = (y2 - dy) * 3.0\n by = (y3 - y2) * 3.0 - cy\n ay = y4 - dy - cy - by\n solutions = sorted(solveCubic(ay, by, cy, dy - y))\n solutions = [t for t in solutions if -0.0 <= t <= 1.0]\n if not solutions:\n return\n\n dx = x1\n cx = (x2 - dx) * 3.0\n bx = (x3 - x2) * 3.0 - cx\n ax = x4 - dx - cx - bx\n\n above = y1 >= y\n lastT = None\n for t in solutions:\n if t == lastT:\n continue\n lastT = t\n t2 = t * t\n t3 = t2 * t\n\n direction = 3 * ay * t2 + 2 * by * t + cy\n incomingGoingUp = outgoingGoingUp = direction > 0.0\n if direction == 0.0:\n direction = 6 * ay * t + 2 * by\n outgoingGoingUp = direction > 0.0\n incomingGoingUp = not outgoingGoingUp\n if direction == 0.0:\n direction = ay\n incomingGoingUp = outgoingGoingUp = direction > 0.0\n\n xt = ax * t3 + bx * t2 + cx * t + dx\n if xt < x:\n continue\n\n if t in (0.0, -0.0):\n if not outgoingGoingUp:\n self._addIntersection(outgoingGoingUp)\n elif t == 1.0:\n if incomingGoingUp:\n self._addIntersection(incomingGoingUp)\n else:\n if incomingGoingUp == outgoingGoingUp:\n self._addIntersection(outgoingGoingUp)\n # else:\n # we're not really intersecting, merely touching\n\n def _qCurveToOne_unfinished(self, bcp, point):\n # XXX need to finish this, for now doing it through a cubic\n # (BasePen implements _qCurveTo in terms of a cubic) will\n # have to do.\n x, y = self.testPoint\n x1, y1 = self._getCurrentPoint()\n x2, y2 = bcp\n x3, y3 = point\n c = y1\n b = (y2 - c) * 2.0\n a = y3 - c - b\n solutions = sorted(solveQuadratic(a, b, c - y))\n solutions = [\n t for t in solutions if ZERO_MINUS_EPSILON <= t <= ONE_PLUS_EPSILON\n ]\n if not solutions:\n return\n # XXX\n\n def _closePath(self):\n if self._getCurrentPoint() != self.firstPoint:\n self.lineTo(self.firstPoint)\n self.firstPoint = None\n\n def _endPath(self):\n """Insideness is not defined for open contours."""\n raise NotImplementedError\n
.venv\Lib\site-packages\fontTools\pens\pointInsidePen.py
pointInsidePen.py
Python
6,547
0.95
0.270833
0.116564
python-kit
709
2023-08-31T14:31:37.709141
MIT
false
3974e5e3becd153ee08f06424a8fb046
"""\n=========\nPointPens\n=========\n\nWhere **SegmentPens** have an intuitive approach to drawing\n(if you're familiar with postscript anyway), the **PointPen**\nis geared towards accessing all the data in the contours of\nthe glyph. A PointPen has a very simple interface, it just\nsteps through all the points in a call from glyph.drawPoints().\nThis allows the caller to provide more data for each point.\nFor instance, whether or not a point is smooth, and its name.\n"""\n\nfrom __future__ import annotations\n\nimport math\nfrom typing import Any, Dict, List, Optional, Tuple\n\nfrom fontTools.misc.loggingTools import LogMixin\nfrom fontTools.misc.transform import DecomposedTransform, Identity\nfrom fontTools.pens.basePen import AbstractPen, MissingComponentError, PenError\n\n__all__ = [\n "AbstractPointPen",\n "BasePointToSegmentPen",\n "PointToSegmentPen",\n "SegmentToPointPen",\n "GuessSmoothPointPen",\n "ReverseContourPointPen",\n]\n\n# Some type aliases to make it easier below\nPoint = Tuple[float, float]\nPointName = Optional[str]\n# [(pt, smooth, name, kwargs)]\nSegmentPointList = List[Tuple[Optional[Point], bool, PointName, Any]]\nSegmentType = Optional[str]\nSegmentList = List[Tuple[SegmentType, SegmentPointList]]\n\n\nclass AbstractPointPen:\n """Baseclass for all PointPens."""\n\n def beginPath(self, identifier: Optional[str] = None, **kwargs: Any) -> None:\n """Start a new sub path."""\n raise NotImplementedError\n\n def endPath(self) -> None:\n """End the current sub path."""\n raise NotImplementedError\n\n def addPoint(\n self,\n pt: Tuple[float, float],\n segmentType: Optional[str] = None,\n smooth: bool = False,\n name: Optional[str] = None,\n identifier: Optional[str] = None,\n **kwargs: Any,\n ) -> None:\n """Add a point to the current sub path."""\n raise NotImplementedError\n\n def addComponent(\n self,\n baseGlyphName: str,\n transformation: Tuple[float, float, float, float, float, float],\n identifier: Optional[str] = None,\n **kwargs: Any,\n ) -> None:\n """Add a sub glyph."""\n raise NotImplementedError\n\n def addVarComponent(\n self,\n glyphName: str,\n transformation: DecomposedTransform,\n location: Dict[str, float],\n identifier: Optional[str] = None,\n **kwargs: Any,\n ) -> None:\n """Add a VarComponent sub glyph. The 'transformation' argument\n must be a DecomposedTransform from the fontTools.misc.transform module,\n and the 'location' argument must be a dictionary mapping axis tags\n to their locations.\n """\n # ttGlyphSet decomposes for us\n raise AttributeError\n\n\nclass BasePointToSegmentPen(AbstractPointPen):\n """\n Base class for retrieving the outline in a segment-oriented\n way. The PointPen protocol is simple yet also a little tricky,\n so when you need an outline presented as segments but you have\n as points, do use this base implementation as it properly takes\n care of all the edge cases.\n """\n\n def __init__(self) -> None:\n self.currentPath = None\n\n def beginPath(self, identifier=None, **kwargs):\n if self.currentPath is not None:\n raise PenError("Path already begun.")\n self.currentPath = []\n\n def _flushContour(self, segments: SegmentList) -> None:\n """Override this method.\n\n It will be called for each non-empty sub path with a list\n of segments: the 'segments' argument.\n\n The segments list contains tuples of length 2:\n (segmentType, points)\n\n segmentType is one of "move", "line", "curve" or "qcurve".\n "move" may only occur as the first segment, and it signifies\n an OPEN path. A CLOSED path does NOT start with a "move", in\n fact it will not contain a "move" at ALL.\n\n The 'points' field in the 2-tuple is a list of point info\n tuples. The list has 1 or more items, a point tuple has\n four items:\n (point, smooth, name, kwargs)\n 'point' is an (x, y) coordinate pair.\n\n For a closed path, the initial moveTo point is defined as\n the last point of the last segment.\n\n The 'points' list of "move" and "line" segments always contains\n exactly one point tuple.\n """\n raise NotImplementedError\n\n def endPath(self) -> None:\n if self.currentPath is None:\n raise PenError("Path not begun.")\n points = self.currentPath\n self.currentPath = None\n if not points:\n return\n if len(points) == 1:\n # Not much more we can do than output a single move segment.\n pt, segmentType, smooth, name, kwargs = points[0]\n segments: SegmentList = [("move", [(pt, smooth, name, kwargs)])]\n self._flushContour(segments)\n return\n segments = []\n if points[0][1] == "move":\n # It's an open contour, insert a "move" segment for the first\n # point and remove that first point from the point list.\n pt, segmentType, smooth, name, kwargs = points[0]\n segments.append(("move", [(pt, smooth, name, kwargs)]))\n points.pop(0)\n else:\n # It's a closed contour. Locate the first on-curve point, and\n # rotate the point list so that it _ends_ with an on-curve\n # point.\n firstOnCurve = None\n for i in range(len(points)):\n segmentType = points[i][1]\n if segmentType is not None:\n firstOnCurve = i\n break\n if firstOnCurve is None:\n # Special case for quadratics: a contour with no on-curve\n # points. Add a "None" point. (See also the Pen protocol's\n # qCurveTo() method and fontTools.pens.basePen.py.)\n points.append((None, "qcurve", None, None, None))\n else:\n points = points[firstOnCurve + 1 :] + points[: firstOnCurve + 1]\n\n currentSegment: SegmentPointList = []\n for pt, segmentType, smooth, name, kwargs in points:\n currentSegment.append((pt, smooth, name, kwargs))\n if segmentType is None:\n continue\n segments.append((segmentType, currentSegment))\n currentSegment = []\n\n self._flushContour(segments)\n\n def addPoint(\n self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs\n ):\n if self.currentPath is None:\n raise PenError("Path not begun")\n self.currentPath.append((pt, segmentType, smooth, name, kwargs))\n\n\nclass PointToSegmentPen(BasePointToSegmentPen):\n """\n Adapter class that converts the PointPen protocol to the\n (Segment)Pen protocol.\n\n NOTE: The segment pen does not support and will drop point names, identifiers\n and kwargs.\n """\n\n def __init__(self, segmentPen, outputImpliedClosingLine: bool = False) -> None:\n BasePointToSegmentPen.__init__(self)\n self.pen = segmentPen\n self.outputImpliedClosingLine = outputImpliedClosingLine\n\n def _flushContour(self, segments):\n if not segments:\n raise PenError("Must have at least one segment.")\n pen = self.pen\n if segments[0][0] == "move":\n # It's an open path.\n closed = False\n points = segments[0][1]\n if len(points) != 1:\n raise PenError(f"Illegal move segment point count: {len(points)}")\n movePt, _, _, _ = points[0]\n del segments[0]\n else:\n # It's a closed path, do a moveTo to the last\n # point of the last segment.\n closed = True\n segmentType, points = segments[-1]\n movePt, _, _, _ = points[-1]\n if movePt is None:\n # quad special case: a contour with no on-curve points contains\n # one "qcurve" segment that ends with a point that's None. We\n # must not output a moveTo() in that case.\n pass\n else:\n pen.moveTo(movePt)\n outputImpliedClosingLine = self.outputImpliedClosingLine\n nSegments = len(segments)\n lastPt = movePt\n for i in range(nSegments):\n segmentType, points = segments[i]\n points = [pt for pt, _, _, _ in points]\n if segmentType == "line":\n if len(points) != 1:\n raise PenError(f"Illegal line segment point count: {len(points)}")\n pt = points[0]\n # For closed contours, a 'lineTo' is always implied from the last oncurve\n # point to the starting point, thus we can omit it when the last and\n # starting point don't overlap.\n # However, when the last oncurve point is a "line" segment and has same\n # coordinates as the starting point of a closed contour, we need to output\n # the closing 'lineTo' explicitly (regardless of the value of the\n # 'outputImpliedClosingLine' option) in order to disambiguate this case from\n # the implied closing 'lineTo', otherwise the duplicate point would be lost.\n # See https://github.com/googlefonts/fontmake/issues/572.\n if (\n i + 1 != nSegments\n or outputImpliedClosingLine\n or not closed\n or pt == lastPt\n ):\n pen.lineTo(pt)\n lastPt = pt\n elif segmentType == "curve":\n pen.curveTo(*points)\n lastPt = points[-1]\n elif segmentType == "qcurve":\n pen.qCurveTo(*points)\n lastPt = points[-1]\n else:\n raise PenError(f"Illegal segmentType: {segmentType}")\n if closed:\n pen.closePath()\n else:\n pen.endPath()\n\n def addComponent(self, glyphName, transform, identifier=None, **kwargs):\n del identifier # unused\n del kwargs # unused\n self.pen.addComponent(glyphName, transform)\n\n\nclass SegmentToPointPen(AbstractPen):\n """\n Adapter class that converts the (Segment)Pen protocol to the\n PointPen protocol.\n """\n\n def __init__(self, pointPen, guessSmooth=True) -> None:\n if guessSmooth:\n self.pen = GuessSmoothPointPen(pointPen)\n else:\n self.pen = pointPen\n self.contour: Optional[List[Tuple[Point, SegmentType]]] = None\n\n def _flushContour(self) -> None:\n pen = self.pen\n pen.beginPath()\n for pt, segmentType in self.contour:\n pen.addPoint(pt, segmentType=segmentType)\n pen.endPath()\n\n def moveTo(self, pt):\n self.contour = []\n self.contour.append((pt, "move"))\n\n def lineTo(self, pt):\n if self.contour is None:\n raise PenError("Contour missing required initial moveTo")\n self.contour.append((pt, "line"))\n\n def curveTo(self, *pts):\n if not pts:\n raise TypeError("Must pass in at least one point")\n if self.contour is None:\n raise PenError("Contour missing required initial moveTo")\n for pt in pts[:-1]:\n self.contour.append((pt, None))\n self.contour.append((pts[-1], "curve"))\n\n def qCurveTo(self, *pts):\n if not pts:\n raise TypeError("Must pass in at least one point")\n if pts[-1] is None:\n self.contour = []\n else:\n if self.contour is None:\n raise PenError("Contour missing required initial moveTo")\n for pt in pts[:-1]:\n self.contour.append((pt, None))\n if pts[-1] is not None:\n self.contour.append((pts[-1], "qcurve"))\n\n def closePath(self):\n if self.contour is None:\n raise PenError("Contour missing required initial moveTo")\n if len(self.contour) > 1 and self.contour[0][0] == self.contour[-1][0]:\n self.contour[0] = self.contour[-1]\n del self.contour[-1]\n else:\n # There's an implied line at the end, replace "move" with "line"\n # for the first point\n pt, tp = self.contour[0]\n if tp == "move":\n self.contour[0] = pt, "line"\n self._flushContour()\n self.contour = None\n\n def endPath(self):\n if self.contour is None:\n raise PenError("Contour missing required initial moveTo")\n self._flushContour()\n self.contour = None\n\n def addComponent(self, glyphName, transform):\n if self.contour is not None:\n raise PenError("Components must be added before or after contours")\n self.pen.addComponent(glyphName, transform)\n\n\nclass GuessSmoothPointPen(AbstractPointPen):\n """\n Filtering PointPen that tries to determine whether an on-curve point\n should be "smooth", ie. that it's a "tangent" point or a "curve" point.\n """\n\n def __init__(self, outPen, error=0.05):\n self._outPen = outPen\n self._error = error\n self._points = None\n\n def _flushContour(self):\n if self._points is None:\n raise PenError("Path not begun")\n points = self._points\n nPoints = len(points)\n if not nPoints:\n return\n if points[0][1] == "move":\n # Open path.\n indices = range(1, nPoints - 1)\n elif nPoints > 1:\n # Closed path. To avoid having to mod the contour index, we\n # simply abuse Python's negative index feature, and start at -1\n indices = range(-1, nPoints - 1)\n else:\n # closed path containing 1 point (!), ignore.\n indices = []\n for i in indices:\n pt, segmentType, _, name, kwargs = points[i]\n if segmentType is None:\n continue\n prev = i - 1\n next = i + 1\n if points[prev][1] is not None and points[next][1] is not None:\n continue\n # At least one of our neighbors is an off-curve point\n pt = points[i][0]\n prevPt = points[prev][0]\n nextPt = points[next][0]\n if pt != prevPt and pt != nextPt:\n dx1, dy1 = pt[0] - prevPt[0], pt[1] - prevPt[1]\n dx2, dy2 = nextPt[0] - pt[0], nextPt[1] - pt[1]\n a1 = math.atan2(dy1, dx1)\n a2 = math.atan2(dy2, dx2)\n if abs(a1 - a2) < self._error:\n points[i] = pt, segmentType, True, name, kwargs\n\n for pt, segmentType, smooth, name, kwargs in points:\n self._outPen.addPoint(pt, segmentType, smooth, name, **kwargs)\n\n def beginPath(self, identifier=None, **kwargs):\n if self._points is not None:\n raise PenError("Path already begun")\n self._points = []\n if identifier is not None:\n kwargs["identifier"] = identifier\n self._outPen.beginPath(**kwargs)\n\n def endPath(self):\n self._flushContour()\n self._outPen.endPath()\n self._points = None\n\n def addPoint(\n self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs\n ):\n if self._points is None:\n raise PenError("Path not begun")\n if identifier is not None:\n kwargs["identifier"] = identifier\n self._points.append((pt, segmentType, False, name, kwargs))\n\n def addComponent(self, glyphName, transformation, identifier=None, **kwargs):\n if self._points is not None:\n raise PenError("Components must be added before or after contours")\n if identifier is not None:\n kwargs["identifier"] = identifier\n self._outPen.addComponent(glyphName, transformation, **kwargs)\n\n def addVarComponent(\n self, glyphName, transformation, location, identifier=None, **kwargs\n ):\n if self._points is not None:\n raise PenError("VarComponents must be added before or after contours")\n if identifier is not None:\n kwargs["identifier"] = identifier\n self._outPen.addVarComponent(glyphName, transformation, location, **kwargs)\n\n\nclass ReverseContourPointPen(AbstractPointPen):\n """\n This is a PointPen that passes outline data to another PointPen, but\n reversing the winding direction of all contours. Components are simply\n passed through unchanged.\n\n Closed contours are reversed in such a way that the first point remains\n the first point.\n """\n\n def __init__(self, outputPointPen):\n self.pen = outputPointPen\n # a place to store the points for the current sub path\n self.currentContour = None\n\n def _flushContour(self):\n pen = self.pen\n contour = self.currentContour\n if not contour:\n pen.beginPath(identifier=self.currentContourIdentifier)\n pen.endPath()\n return\n\n closed = contour[0][1] != "move"\n if not closed:\n lastSegmentType = "move"\n else:\n # Remove the first point and insert it at the end. When\n # the list of points gets reversed, this point will then\n # again be at the start. In other words, the following\n # will hold:\n # for N in range(len(originalContour)):\n # originalContour[N] == reversedContour[-N]\n contour.append(contour.pop(0))\n # Find the first on-curve point.\n firstOnCurve = None\n for i in range(len(contour)):\n if contour[i][1] is not None:\n firstOnCurve = i\n break\n if firstOnCurve is None:\n # There are no on-curve points, be basically have to\n # do nothing but contour.reverse().\n lastSegmentType = None\n else:\n lastSegmentType = contour[firstOnCurve][1]\n\n contour.reverse()\n if not closed:\n # Open paths must start with a move, so we simply dump\n # all off-curve points leading up to the first on-curve.\n while contour[0][1] is None:\n contour.pop(0)\n pen.beginPath(identifier=self.currentContourIdentifier)\n for pt, nextSegmentType, smooth, name, kwargs in contour:\n if nextSegmentType is not None:\n segmentType = lastSegmentType\n lastSegmentType = nextSegmentType\n else:\n segmentType = None\n pen.addPoint(\n pt, segmentType=segmentType, smooth=smooth, name=name, **kwargs\n )\n pen.endPath()\n\n def beginPath(self, identifier=None, **kwargs):\n if self.currentContour is not None:\n raise PenError("Path already begun")\n self.currentContour = []\n self.currentContourIdentifier = identifier\n self.onCurve = []\n\n def endPath(self):\n if self.currentContour is None:\n raise PenError("Path not begun")\n self._flushContour()\n self.currentContour = None\n\n def addPoint(\n self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs\n ):\n if self.currentContour is None:\n raise PenError("Path not begun")\n if identifier is not None:\n kwargs["identifier"] = identifier\n self.currentContour.append((pt, segmentType, smooth, name, kwargs))\n\n def addComponent(self, glyphName, transform, identifier=None, **kwargs):\n if self.currentContour is not None:\n raise PenError("Components must be added before or after contours")\n self.pen.addComponent(glyphName, transform, identifier=identifier, **kwargs)\n\n\nclass DecomposingPointPen(LogMixin, AbstractPointPen):\n """Implements a 'addComponent' method that decomposes components\n (i.e. draws them onto self as simple contours).\n It can also be used as a mixin class (e.g. see DecomposingRecordingPointPen).\n\n You must override beginPath, addPoint, endPath. You may\n additionally override addVarComponent and addComponent.\n\n By default a warning message is logged when a base glyph is missing;\n set the class variable ``skipMissingComponents`` to False if you want\n all instances of a sub-class to raise a :class:`MissingComponentError`\n exception by default.\n """\n\n skipMissingComponents = True\n # alias error for convenience\n MissingComponentError = MissingComponentError\n\n def __init__(\n self,\n glyphSet,\n *args,\n skipMissingComponents=None,\n reverseFlipped=False,\n **kwargs,\n ):\n """Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced\n as components are looked up by their name.\n\n If the optional 'reverseFlipped' argument is True, components whose transformation\n matrix has a negative determinant will be decomposed with a reversed path direction\n to compensate for the flip.\n\n The optional 'skipMissingComponents' argument can be set to True/False to\n override the homonymous class attribute for a given pen instance.\n """\n super().__init__(*args, **kwargs)\n self.glyphSet = glyphSet\n self.skipMissingComponents = (\n self.__class__.skipMissingComponents\n if skipMissingComponents is None\n else skipMissingComponents\n )\n self.reverseFlipped = reverseFlipped\n\n def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):\n """Transform the points of the base glyph and draw it onto self.\n\n The `identifier` parameter and any extra kwargs are ignored.\n """\n from fontTools.pens.transformPen import TransformPointPen\n\n try:\n glyph = self.glyphSet[baseGlyphName]\n except KeyError:\n if not self.skipMissingComponents:\n raise MissingComponentError(baseGlyphName)\n self.log.warning(\n "glyph '%s' is missing from glyphSet; skipped" % baseGlyphName\n )\n else:\n pen = self\n if transformation != Identity:\n pen = TransformPointPen(pen, transformation)\n if self.reverseFlipped:\n # if the transformation has a negative determinant, it will\n # reverse the contour direction of the component\n a, b, c, d = transformation[:4]\n if a * d - b * c < 0:\n pen = ReverseContourPointPen(pen)\n glyph.drawPoints(pen)\n
.venv\Lib\site-packages\fontTools\pens\pointPen.py
pointPen.py
Python
23,339
0.95
0.233169
0.101504
python-kit
179
2024-01-03T14:47:24.710897
BSD-3-Clause
false
3a4f51f0d8287b331bd614b145ae7b7e
from fontTools.pens.basePen import BasePen\n\n\n__all__ = ["QtPen"]\n\n\nclass QtPen(BasePen):\n def __init__(self, glyphSet, path=None):\n BasePen.__init__(self, glyphSet)\n if path is None:\n from PyQt5.QtGui import QPainterPath\n\n path = QPainterPath()\n self.path = path\n\n def _moveTo(self, p):\n self.path.moveTo(*p)\n\n def _lineTo(self, p):\n self.path.lineTo(*p)\n\n def _curveToOne(self, p1, p2, p3):\n self.path.cubicTo(*p1, *p2, *p3)\n\n def _qCurveToOne(self, p1, p2):\n self.path.quadTo(*p1, *p2)\n\n def _closePath(self):\n self.path.closeSubpath()\n
.venv\Lib\site-packages\fontTools\pens\qtPen.py
qtPen.py
Python
663
0.85
0.275862
0
vue-tools
295
2024-01-06T10:48:26.108539
BSD-3-Clause
false
384d96ea5a7698ec9c2907df75427cc2
# Copyright 2016 Google Inc. All Rights Reserved.\n# Copyright 2023 Behdad Esfahbod. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom fontTools.qu2cu import quadratic_to_curves\nfrom fontTools.pens.filterPen import ContourFilterPen\nfrom fontTools.pens.reverseContourPen import ReverseContourPen\nimport math\n\n\nclass Qu2CuPen(ContourFilterPen):\n """A filter pen to convert quadratic bezier splines to cubic curves\n using the FontTools SegmentPen protocol.\n\n Args:\n\n other_pen: another SegmentPen used to draw the transformed outline.\n max_err: maximum approximation error in font units. For optimal results,\n if you know the UPEM of the font, we recommend setting this to a\n value equal, or close to UPEM / 1000.\n reverse_direction: flip the contours' direction but keep starting point.\n stats: a dictionary counting the point numbers of cubic segments.\n """\n\n def __init__(\n self,\n other_pen,\n max_err,\n all_cubic=False,\n reverse_direction=False,\n stats=None,\n ):\n if reverse_direction:\n other_pen = ReverseContourPen(other_pen)\n super().__init__(other_pen)\n self.all_cubic = all_cubic\n self.max_err = max_err\n self.stats = stats\n\n def _quadratics_to_curve(self, q):\n curves = quadratic_to_curves(q, self.max_err, all_cubic=self.all_cubic)\n if self.stats is not None:\n for curve in curves:\n n = str(len(curve) - 2)\n self.stats[n] = self.stats.get(n, 0) + 1\n for curve in curves:\n if len(curve) == 4:\n yield ("curveTo", curve[1:])\n else:\n yield ("qCurveTo", curve[1:])\n\n def filterContour(self, contour):\n quadratics = []\n currentPt = None\n newContour = []\n for op, args in contour:\n if op == "qCurveTo" and (\n self.all_cubic or (len(args) > 2 and args[-1] is not None)\n ):\n if args[-1] is None:\n raise NotImplementedError(\n "oncurve-less contours with all_cubic not implemented"\n )\n quadratics.append((currentPt,) + args)\n else:\n if quadratics:\n newContour.extend(self._quadratics_to_curve(quadratics))\n quadratics = []\n newContour.append((op, args))\n currentPt = args[-1] if args else None\n if quadratics:\n newContour.extend(self._quadratics_to_curve(quadratics))\n\n if not self.all_cubic:\n # Add back implicit oncurve points\n contour = newContour\n newContour = []\n for op, args in contour:\n if op == "qCurveTo" and newContour and newContour[-1][0] == "qCurveTo":\n pt0 = newContour[-1][1][-2]\n pt1 = newContour[-1][1][-1]\n pt2 = args[0]\n if (\n pt1 is not None\n and math.isclose(pt2[0] - pt1[0], pt1[0] - pt0[0])\n and math.isclose(pt2[1] - pt1[1], pt1[1] - pt0[1])\n ):\n newArgs = newContour[-1][1][:-1] + args\n newContour[-1] = (op, newArgs)\n continue\n\n newContour.append((op, args))\n\n return newContour\n
.venv\Lib\site-packages\fontTools\pens\qu2cuPen.py
qu2cuPen.py
Python
4,090
0.95
0.2
0.159574
python-kit
660
2024-12-03T06:21:07.827767
Apache-2.0
false
f331080d163f4ce9f066289afd5c8605
from fontTools.pens.basePen import BasePen\n\nfrom Quartz.CoreGraphics import CGPathCreateMutable, CGPathMoveToPoint\nfrom Quartz.CoreGraphics import CGPathAddLineToPoint, CGPathAddCurveToPoint\nfrom Quartz.CoreGraphics import CGPathAddQuadCurveToPoint, CGPathCloseSubpath\n\n\n__all__ = ["QuartzPen"]\n\n\nclass QuartzPen(BasePen):\n """A pen that creates a CGPath\n\n Parameters\n - path: an optional CGPath to add to\n - xform: an optional CGAffineTransform to apply to the path\n """\n\n def __init__(self, glyphSet, path=None, xform=None):\n BasePen.__init__(self, glyphSet)\n if path is None:\n path = CGPathCreateMutable()\n self.path = path\n self.xform = xform\n\n def _moveTo(self, pt):\n x, y = pt\n CGPathMoveToPoint(self.path, self.xform, x, y)\n\n def _lineTo(self, pt):\n x, y = pt\n CGPathAddLineToPoint(self.path, self.xform, x, y)\n\n def _curveToOne(self, p1, p2, p3):\n (x1, y1), (x2, y2), (x3, y3) = p1, p2, p3\n CGPathAddCurveToPoint(self.path, self.xform, x1, y1, x2, y2, x3, y3)\n\n def _qCurveToOne(self, p1, p2):\n (x1, y1), (x2, y2) = p1, p2\n CGPathAddQuadCurveToPoint(self.path, self.xform, x1, y1, x2, y2)\n\n def _closePath(self):\n CGPathCloseSubpath(self.path)\n
.venv\Lib\site-packages\fontTools\pens\quartzPen.py
quartzPen.py
Python
1,330
0.85
0.186047
0
react-lib
706
2024-05-08T01:55:59.809710
MIT
false
bdc2a9c6fb1370731eac440c861fd535
"""Pen recording operations that can be accessed or replayed."""\n\nfrom fontTools.pens.basePen import AbstractPen, DecomposingPen\nfrom fontTools.pens.pointPen import AbstractPointPen, DecomposingPointPen\n\n\n__all__ = [\n "replayRecording",\n "RecordingPen",\n "DecomposingRecordingPen",\n "DecomposingRecordingPointPen",\n "RecordingPointPen",\n "lerpRecordings",\n]\n\n\ndef replayRecording(recording, pen):\n """Replay a recording, as produced by RecordingPen or DecomposingRecordingPen,\n to a pen.\n\n Note that recording does not have to be produced by those pens.\n It can be any iterable of tuples of method name and tuple-of-arguments.\n Likewise, pen can be any objects receiving those method calls.\n """\n for operator, operands in recording:\n getattr(pen, operator)(*operands)\n\n\nclass RecordingPen(AbstractPen):\n """Pen recording operations that can be accessed or replayed.\n\n The recording can be accessed as pen.value; or replayed using\n pen.replay(otherPen).\n\n :Example:\n .. code-block::\n\n from fontTools.ttLib import TTFont\n from fontTools.pens.recordingPen import RecordingPen\n\n glyph_name = 'dollar'\n font_path = 'MyFont.otf'\n\n font = TTFont(font_path)\n glyphset = font.getGlyphSet()\n glyph = glyphset[glyph_name]\n\n pen = RecordingPen()\n glyph.draw(pen)\n print(pen.value)\n """\n\n def __init__(self):\n self.value = []\n\n def moveTo(self, p0):\n self.value.append(("moveTo", (p0,)))\n\n def lineTo(self, p1):\n self.value.append(("lineTo", (p1,)))\n\n def qCurveTo(self, *points):\n self.value.append(("qCurveTo", points))\n\n def curveTo(self, *points):\n self.value.append(("curveTo", points))\n\n def closePath(self):\n self.value.append(("closePath", ()))\n\n def endPath(self):\n self.value.append(("endPath", ()))\n\n def addComponent(self, glyphName, transformation):\n self.value.append(("addComponent", (glyphName, transformation)))\n\n def addVarComponent(self, glyphName, transformation, location):\n self.value.append(("addVarComponent", (glyphName, transformation, location)))\n\n def replay(self, pen):\n replayRecording(self.value, pen)\n\n draw = replay\n\n\nclass DecomposingRecordingPen(DecomposingPen, RecordingPen):\n """Same as RecordingPen, except that it doesn't keep components\n as references, but draws them decomposed as regular contours.\n\n The constructor takes a required 'glyphSet' positional argument,\n a dictionary of glyph objects (i.e. with a 'draw' method) keyed\n by thir name; other arguments are forwarded to the DecomposingPen's\n constructor::\n\n >>> class SimpleGlyph(object):\n ... def draw(self, pen):\n ... pen.moveTo((0, 0))\n ... pen.curveTo((1, 1), (2, 2), (3, 3))\n ... pen.closePath()\n >>> class CompositeGlyph(object):\n ... def draw(self, pen):\n ... pen.addComponent('a', (1, 0, 0, 1, -1, 1))\n >>> class MissingComponent(object):\n ... def draw(self, pen):\n ... pen.addComponent('foobar', (1, 0, 0, 1, 0, 0))\n >>> class FlippedComponent(object):\n ... def draw(self, pen):\n ... pen.addComponent('a', (-1, 0, 0, 1, 0, 0))\n >>> glyphSet = {\n ... 'a': SimpleGlyph(),\n ... 'b': CompositeGlyph(),\n ... 'c': MissingComponent(),\n ... 'd': FlippedComponent(),\n ... }\n >>> for name, glyph in sorted(glyphSet.items()):\n ... pen = DecomposingRecordingPen(glyphSet)\n ... try:\n ... glyph.draw(pen)\n ... except pen.MissingComponentError:\n ... pass\n ... print("{}: {}".format(name, pen.value))\n a: [('moveTo', ((0, 0),)), ('curveTo', ((1, 1), (2, 2), (3, 3))), ('closePath', ())]\n b: [('moveTo', ((-1, 1),)), ('curveTo', ((0, 2), (1, 3), (2, 4))), ('closePath', ())]\n c: []\n d: [('moveTo', ((0, 0),)), ('curveTo', ((-1, 1), (-2, 2), (-3, 3))), ('closePath', ())]\n\n >>> for name, glyph in sorted(glyphSet.items()):\n ... pen = DecomposingRecordingPen(\n ... glyphSet, skipMissingComponents=True, reverseFlipped=True,\n ... )\n ... glyph.draw(pen)\n ... print("{}: {}".format(name, pen.value))\n a: [('moveTo', ((0, 0),)), ('curveTo', ((1, 1), (2, 2), (3, 3))), ('closePath', ())]\n b: [('moveTo', ((-1, 1),)), ('curveTo', ((0, 2), (1, 3), (2, 4))), ('closePath', ())]\n c: []\n d: [('moveTo', ((0, 0),)), ('lineTo', ((-3, 3),)), ('curveTo', ((-2, 2), (-1, 1), (0, 0))), ('closePath', ())]\n """\n\n # raises MissingComponentError(KeyError) if base glyph is not found in glyphSet\n skipMissingComponents = False\n\n\nclass RecordingPointPen(AbstractPointPen):\n """PointPen recording operations that can be accessed or replayed.\n\n The recording can be accessed as pen.value; or replayed using\n pointPen.replay(otherPointPen).\n\n :Example:\n .. code-block::\n\n from defcon import Font\n from fontTools.pens.recordingPen import RecordingPointPen\n\n glyph_name = 'a'\n font_path = 'MyFont.ufo'\n\n font = Font(font_path)\n glyph = font[glyph_name]\n\n pen = RecordingPointPen()\n glyph.drawPoints(pen)\n print(pen.value)\n\n new_glyph = font.newGlyph('b')\n pen.replay(new_glyph.getPointPen())\n """\n\n def __init__(self):\n self.value = []\n\n def beginPath(self, identifier=None, **kwargs):\n if identifier is not None:\n kwargs["identifier"] = identifier\n self.value.append(("beginPath", (), kwargs))\n\n def endPath(self):\n self.value.append(("endPath", (), {}))\n\n def addPoint(\n self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs\n ):\n if identifier is not None:\n kwargs["identifier"] = identifier\n self.value.append(("addPoint", (pt, segmentType, smooth, name), kwargs))\n\n def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):\n if identifier is not None:\n kwargs["identifier"] = identifier\n self.value.append(("addComponent", (baseGlyphName, transformation), kwargs))\n\n def addVarComponent(\n self, baseGlyphName, transformation, location, identifier=None, **kwargs\n ):\n if identifier is not None:\n kwargs["identifier"] = identifier\n self.value.append(\n ("addVarComponent", (baseGlyphName, transformation, location), kwargs)\n )\n\n def replay(self, pointPen):\n for operator, args, kwargs in self.value:\n getattr(pointPen, operator)(*args, **kwargs)\n\n drawPoints = replay\n\n\nclass DecomposingRecordingPointPen(DecomposingPointPen, RecordingPointPen):\n """Same as RecordingPointPen, except that it doesn't keep components\n as references, but draws them decomposed as regular contours.\n\n The constructor takes a required 'glyphSet' positional argument,\n a dictionary of pointPen-drawable glyph objects (i.e. with a 'drawPoints' method)\n keyed by thir name; other arguments are forwarded to the DecomposingPointPen's\n constructor::\n\n >>> from pprint import pprint\n >>> class SimpleGlyph(object):\n ... def drawPoints(self, pen):\n ... pen.beginPath()\n ... pen.addPoint((0, 0), "line")\n ... pen.addPoint((1, 1))\n ... pen.addPoint((2, 2))\n ... pen.addPoint((3, 3), "curve")\n ... pen.endPath()\n >>> class CompositeGlyph(object):\n ... def drawPoints(self, pen):\n ... pen.addComponent('a', (1, 0, 0, 1, -1, 1))\n >>> class MissingComponent(object):\n ... def drawPoints(self, pen):\n ... pen.addComponent('foobar', (1, 0, 0, 1, 0, 0))\n >>> class FlippedComponent(object):\n ... def drawPoints(self, pen):\n ... pen.addComponent('a', (-1, 0, 0, 1, 0, 0))\n >>> glyphSet = {\n ... 'a': SimpleGlyph(),\n ... 'b': CompositeGlyph(),\n ... 'c': MissingComponent(),\n ... 'd': FlippedComponent(),\n ... }\n >>> for name, glyph in sorted(glyphSet.items()):\n ... pen = DecomposingRecordingPointPen(glyphSet)\n ... try:\n ... glyph.drawPoints(pen)\n ... except pen.MissingComponentError:\n ... pass\n ... pprint({name: pen.value})\n {'a': [('beginPath', (), {}),\n ('addPoint', ((0, 0), 'line', False, None), {}),\n ('addPoint', ((1, 1), None, False, None), {}),\n ('addPoint', ((2, 2), None, False, None), {}),\n ('addPoint', ((3, 3), 'curve', False, None), {}),\n ('endPath', (), {})]}\n {'b': [('beginPath', (), {}),\n ('addPoint', ((-1, 1), 'line', False, None), {}),\n ('addPoint', ((0, 2), None, False, None), {}),\n ('addPoint', ((1, 3), None, False, None), {}),\n ('addPoint', ((2, 4), 'curve', False, None), {}),\n ('endPath', (), {})]}\n {'c': []}\n {'d': [('beginPath', (), {}),\n ('addPoint', ((0, 0), 'line', False, None), {}),\n ('addPoint', ((-1, 1), None, False, None), {}),\n ('addPoint', ((-2, 2), None, False, None), {}),\n ('addPoint', ((-3, 3), 'curve', False, None), {}),\n ('endPath', (), {})]}\n\n >>> for name, glyph in sorted(glyphSet.items()):\n ... pen = DecomposingRecordingPointPen(\n ... glyphSet, skipMissingComponents=True, reverseFlipped=True,\n ... )\n ... glyph.drawPoints(pen)\n ... pprint({name: pen.value})\n {'a': [('beginPath', (), {}),\n ('addPoint', ((0, 0), 'line', False, None), {}),\n ('addPoint', ((1, 1), None, False, None), {}),\n ('addPoint', ((2, 2), None, False, None), {}),\n ('addPoint', ((3, 3), 'curve', False, None), {}),\n ('endPath', (), {})]}\n {'b': [('beginPath', (), {}),\n ('addPoint', ((-1, 1), 'line', False, None), {}),\n ('addPoint', ((0, 2), None, False, None), {}),\n ('addPoint', ((1, 3), None, False, None), {}),\n ('addPoint', ((2, 4), 'curve', False, None), {}),\n ('endPath', (), {})]}\n {'c': []}\n {'d': [('beginPath', (), {}),\n ('addPoint', ((0, 0), 'curve', False, None), {}),\n ('addPoint', ((-3, 3), 'line', False, None), {}),\n ('addPoint', ((-2, 2), None, False, None), {}),\n ('addPoint', ((-1, 1), None, False, None), {}),\n ('endPath', (), {})]}\n """\n\n # raises MissingComponentError(KeyError) if base glyph is not found in glyphSet\n skipMissingComponents = False\n\n\ndef lerpRecordings(recording1, recording2, factor=0.5):\n """Linearly interpolate between two recordings. The recordings\n must be decomposed, i.e. they must not contain any components.\n\n Factor is typically between 0 and 1. 0 means the first recording,\n 1 means the second recording, and 0.5 means the average of the\n two recordings. Other values are possible, and can be useful to\n extrapolate. Defaults to 0.5.\n\n Returns a generator with the new recording.\n """\n if len(recording1) != len(recording2):\n raise ValueError(\n "Mismatched lengths: %d and %d" % (len(recording1), len(recording2))\n )\n for (op1, args1), (op2, args2) in zip(recording1, recording2):\n if op1 != op2:\n raise ValueError("Mismatched operations: %s, %s" % (op1, op2))\n if op1 == "addComponent":\n raise ValueError("Cannot interpolate components")\n else:\n mid_args = [\n (x1 + (x2 - x1) * factor, y1 + (y2 - y1) * factor)\n for (x1, y1), (x2, y2) in zip(args1, args2)\n ]\n yield (op1, mid_args)\n\n\nif __name__ == "__main__":\n pen = RecordingPen()\n pen.moveTo((0, 0))\n pen.lineTo((0, 100))\n pen.curveTo((50, 75), (60, 50), (50, 25))\n pen.closePath()\n from pprint import pprint\n\n pprint(pen.value)\n
.venv\Lib\site-packages\fontTools\pens\recordingPen.py
recordingPen.py
Python
12,824
0.95
0.176119
0.007299
python-kit
641
2025-07-07T07:51:52.502949
MIT
false
bd74d51220a076d0a83b387c4d3dfcf0
from fontTools.pens.basePen import BasePen\nfrom reportlab.graphics.shapes import Path\n\n\n__all__ = ["ReportLabPen"]\n\n\nclass ReportLabPen(BasePen):\n """A pen for drawing onto a ``reportlab.graphics.shapes.Path`` object."""\n\n def __init__(self, glyphSet, path=None):\n BasePen.__init__(self, glyphSet)\n if path is None:\n path = Path()\n self.path = path\n\n def _moveTo(self, p):\n (x, y) = p\n self.path.moveTo(x, y)\n\n def _lineTo(self, p):\n (x, y) = p\n self.path.lineTo(x, y)\n\n def _curveToOne(self, p1, p2, p3):\n (x1, y1) = p1\n (x2, y2) = p2\n (x3, y3) = p3\n self.path.curveTo(x1, y1, x2, y2, x3, y3)\n\n def _closePath(self):\n self.path.closePath()\n\n\nif __name__ == "__main__":\n import sys\n\n if len(sys.argv) < 3:\n print(\n "Usage: reportLabPen.py <OTF/TTF font> <glyphname> [<image file to create>]"\n )\n print(\n " If no image file name is created, by default <glyphname>.png is created."\n )\n print(" example: reportLabPen.py Arial.TTF R test.png")\n print(\n " (The file format will be PNG, regardless of the image file name supplied)"\n )\n sys.exit(0)\n\n from fontTools.ttLib import TTFont\n from reportlab.lib import colors\n\n path = sys.argv[1]\n glyphName = sys.argv[2]\n if len(sys.argv) > 3:\n imageFile = sys.argv[3]\n else:\n imageFile = "%s.png" % glyphName\n\n font = TTFont(path) # it would work just as well with fontTools.t1Lib.T1Font\n gs = font.getGlyphSet()\n pen = ReportLabPen(gs, Path(fillColor=colors.red, strokeWidth=5))\n g = gs[glyphName]\n g.draw(pen)\n\n w, h = g.width, 1000\n from reportlab.graphics import renderPM\n from reportlab.graphics.shapes import Group, Drawing, scale\n\n # Everything is wrapped in a group to allow transformations.\n g = Group(pen.path)\n g.translate(0, 200)\n g.scale(0.3, 0.3)\n\n d = Drawing(w, h)\n d.add(g)\n\n renderPM.drawToFile(d, imageFile, fmt="PNG")\n
.venv\Lib\site-packages\fontTools\pens\reportLabPen.py
reportLabPen.py
Python
2,145
0.95
0.139241
0.016667
node-utils
838
2023-07-30T11:10:33.316050
BSD-3-Clause
false
d47c6e8289c9d725a806e651a6bd4c99
from fontTools.misc.arrayTools import pairwise\nfrom fontTools.pens.filterPen import ContourFilterPen\n\n\n__all__ = ["reversedContour", "ReverseContourPen"]\n\n\nclass ReverseContourPen(ContourFilterPen):\n """Filter pen that passes outline data to another pen, but reversing\n the winding direction of all contours. Components are simply passed\n through unchanged.\n\n Closed contours are reversed in such a way that the first point remains\n the first point.\n """\n\n def __init__(self, outPen, outputImpliedClosingLine=False):\n super().__init__(outPen)\n self.outputImpliedClosingLine = outputImpliedClosingLine\n\n def filterContour(self, contour):\n return reversedContour(contour, self.outputImpliedClosingLine)\n\n\ndef reversedContour(contour, outputImpliedClosingLine=False):\n """Generator that takes a list of pen's (operator, operands) tuples,\n and yields them with the winding direction reversed.\n """\n if not contour:\n return # nothing to do, stop iteration\n\n # valid contours must have at least a starting and ending command,\n # can't have one without the other\n assert len(contour) > 1, "invalid contour"\n\n # the type of the last command determines if the contour is closed\n contourType = contour.pop()[0]\n assert contourType in ("endPath", "closePath")\n closed = contourType == "closePath"\n\n firstType, firstPts = contour.pop(0)\n assert firstType in ("moveTo", "qCurveTo"), (\n "invalid initial segment type: %r" % firstType\n )\n firstOnCurve = firstPts[-1]\n if firstType == "qCurveTo":\n # special case for TrueType paths contaning only off-curve points\n assert firstOnCurve is None, "off-curve only paths must end with 'None'"\n assert not contour, "only one qCurveTo allowed per off-curve path"\n firstPts = (firstPts[0],) + tuple(reversed(firstPts[1:-1])) + (None,)\n\n if not contour:\n # contour contains only one segment, nothing to reverse\n if firstType == "moveTo":\n closed = False # single-point paths can't be closed\n else:\n closed = True # off-curve paths are closed by definition\n yield firstType, firstPts\n else:\n lastType, lastPts = contour[-1]\n lastOnCurve = lastPts[-1]\n if closed:\n # for closed paths, we keep the starting point\n yield firstType, firstPts\n if firstOnCurve != lastOnCurve:\n # emit an implied line between the last and first points\n yield "lineTo", (lastOnCurve,)\n contour[-1] = (lastType, tuple(lastPts[:-1]) + (firstOnCurve,))\n\n if len(contour) > 1:\n secondType, secondPts = contour[0]\n else:\n # contour has only two points, the second and last are the same\n secondType, secondPts = lastType, lastPts\n\n if not outputImpliedClosingLine:\n # if a lineTo follows the initial moveTo, after reversing it\n # will be implied by the closePath, so we don't emit one;\n # unless the lineTo and moveTo overlap, in which case we keep the\n # duplicate points\n if secondType == "lineTo" and firstPts != secondPts:\n del contour[0]\n if contour:\n contour[-1] = (lastType, tuple(lastPts[:-1]) + secondPts)\n else:\n # for open paths, the last point will become the first\n yield firstType, (lastOnCurve,)\n contour[-1] = (lastType, tuple(lastPts[:-1]) + (firstOnCurve,))\n\n # we iterate over all segment pairs in reverse order, and yield\n # each one with the off-curve points reversed (if any), and\n # with the on-curve point of the following segment\n for (curType, curPts), (_, nextPts) in pairwise(contour, reverse=True):\n yield curType, tuple(reversed(curPts[:-1])) + (nextPts[-1],)\n\n yield "closePath" if closed else "endPath", ()\n
.venv\Lib\site-packages\fontTools\pens\reverseContourPen.py
reverseContourPen.py
Python
4,118
0.95
0.229167
0.202532
python-kit
220
2024-12-06T15:04:11.827736
MIT
false
2f8a9714fac134b98d64b1c9d6a9fcf9
from fontTools.misc.roundTools import noRound, otRound\nfrom fontTools.misc.transform import Transform\nfrom fontTools.pens.filterPen import FilterPen, FilterPointPen\n\n\n__all__ = ["RoundingPen", "RoundingPointPen"]\n\n\nclass RoundingPen(FilterPen):\n """\n Filter pen that rounds point coordinates and component XY offsets to integer. For\n rounding the component transform values, a separate round function can be passed to\n the pen.\n\n >>> from fontTools.pens.recordingPen import RecordingPen\n >>> recpen = RecordingPen()\n >>> roundpen = RoundingPen(recpen)\n >>> roundpen.moveTo((0.4, 0.6))\n >>> roundpen.lineTo((1.6, 2.5))\n >>> roundpen.qCurveTo((2.4, 4.6), (3.3, 5.7), (4.9, 6.1))\n >>> roundpen.curveTo((6.4, 8.6), (7.3, 9.7), (8.9, 10.1))\n >>> roundpen.addComponent("a", (1.5, 0, 0, 1.5, 10.5, -10.5))\n >>> recpen.value == [\n ... ('moveTo', ((0, 1),)),\n ... ('lineTo', ((2, 3),)),\n ... ('qCurveTo', ((2, 5), (3, 6), (5, 6))),\n ... ('curveTo', ((6, 9), (7, 10), (9, 10))),\n ... ('addComponent', ('a', (1.5, 0, 0, 1.5, 11, -10))),\n ... ]\n True\n """\n\n def __init__(self, outPen, roundFunc=otRound, transformRoundFunc=noRound):\n super().__init__(outPen)\n self.roundFunc = roundFunc\n self.transformRoundFunc = transformRoundFunc\n\n def moveTo(self, pt):\n self._outPen.moveTo((self.roundFunc(pt[0]), self.roundFunc(pt[1])))\n\n def lineTo(self, pt):\n self._outPen.lineTo((self.roundFunc(pt[0]), self.roundFunc(pt[1])))\n\n def curveTo(self, *points):\n self._outPen.curveTo(\n *((self.roundFunc(x), self.roundFunc(y)) for x, y in points)\n )\n\n def qCurveTo(self, *points):\n self._outPen.qCurveTo(\n *((self.roundFunc(x), self.roundFunc(y)) for x, y in points)\n )\n\n def addComponent(self, glyphName, transformation):\n xx, xy, yx, yy, dx, dy = transformation\n self._outPen.addComponent(\n glyphName,\n Transform(\n self.transformRoundFunc(xx),\n self.transformRoundFunc(xy),\n self.transformRoundFunc(yx),\n self.transformRoundFunc(yy),\n self.roundFunc(dx),\n self.roundFunc(dy),\n ),\n )\n\n\nclass RoundingPointPen(FilterPointPen):\n """\n Filter point pen that rounds point coordinates and component XY offsets to integer.\n For rounding the component scale values, a separate round function can be passed to\n the pen.\n\n >>> from fontTools.pens.recordingPen import RecordingPointPen\n >>> recpen = RecordingPointPen()\n >>> roundpen = RoundingPointPen(recpen)\n >>> roundpen.beginPath()\n >>> roundpen.addPoint((0.4, 0.6), 'line')\n >>> roundpen.addPoint((1.6, 2.5), 'line')\n >>> roundpen.addPoint((2.4, 4.6))\n >>> roundpen.addPoint((3.3, 5.7))\n >>> roundpen.addPoint((4.9, 6.1), 'qcurve')\n >>> roundpen.endPath()\n >>> roundpen.addComponent("a", (1.5, 0, 0, 1.5, 10.5, -10.5))\n >>> recpen.value == [\n ... ('beginPath', (), {}),\n ... ('addPoint', ((0, 1), 'line', False, None), {}),\n ... ('addPoint', ((2, 3), 'line', False, None), {}),\n ... ('addPoint', ((2, 5), None, False, None), {}),\n ... ('addPoint', ((3, 6), None, False, None), {}),\n ... ('addPoint', ((5, 6), 'qcurve', False, None), {}),\n ... ('endPath', (), {}),\n ... ('addComponent', ('a', (1.5, 0, 0, 1.5, 11, -10)), {}),\n ... ]\n True\n """\n\n def __init__(self, outPen, roundFunc=otRound, transformRoundFunc=noRound):\n super().__init__(outPen)\n self.roundFunc = roundFunc\n self.transformRoundFunc = transformRoundFunc\n\n def addPoint(\n self, pt, segmentType=None, smooth=False, name=None, identifier=None, **kwargs\n ):\n self._outPen.addPoint(\n (self.roundFunc(pt[0]), self.roundFunc(pt[1])),\n segmentType=segmentType,\n smooth=smooth,\n name=name,\n identifier=identifier,\n **kwargs,\n )\n\n def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):\n xx, xy, yx, yy, dx, dy = transformation\n self._outPen.addComponent(\n baseGlyphName=baseGlyphName,\n transformation=Transform(\n self.transformRoundFunc(xx),\n self.transformRoundFunc(xy),\n self.transformRoundFunc(yx),\n self.transformRoundFunc(yy),\n self.roundFunc(dx),\n self.roundFunc(dy),\n ),\n identifier=identifier,\n **kwargs,\n )\n
.venv\Lib\site-packages\fontTools\pens\roundingPen.py
roundingPen.py
Python
4,779
0.85
0.115385
0.035398
react-lib
861
2024-12-03T01:40:13.058690
BSD-3-Clause
false
92fde0c7a43e425a63caf3fec2531e6e
from typing import Callable\nfrom fontTools.pens.basePen import BasePen\n\n\ndef pointToString(pt, ntos=str):\n return " ".join(ntos(i) for i in pt)\n\n\nclass SVGPathPen(BasePen):\n """Pen to draw SVG path d commands.\n\n Args:\n glyphSet: a dictionary of drawable glyph objects keyed by name\n used to resolve component references in composite glyphs.\n ntos: a callable that takes a number and returns a string, to\n customize how numbers are formatted (default: str).\n\n :Example:\n .. code-block::\n\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((0, 0))\n >>> pen.lineTo((1, 1))\n >>> pen.curveTo((2, 2), (3, 3), (4, 4))\n >>> pen.closePath()\n >>> pen.getCommands()\n 'M0 0 1 1C2 2 3 3 4 4Z'\n\n Note:\n Fonts have a coordinate system where Y grows up, whereas in SVG,\n Y grows down. As such, rendering path data from this pen in\n SVG typically results in upside-down glyphs. You can fix this\n by wrapping the data from this pen in an SVG group element with\n transform, or wrap this pen in a transform pen. For example:\n .. code-block:: python\n\n spen = svgPathPen.SVGPathPen(glyphset)\n pen= TransformPen(spen , (1, 0, 0, -1, 0, 0))\n glyphset[glyphname].draw(pen)\n print(tpen.getCommands())\n """\n\n def __init__(self, glyphSet, ntos: Callable[[float], str] = str):\n BasePen.__init__(self, glyphSet)\n self._commands = []\n self._lastCommand = None\n self._lastX = None\n self._lastY = None\n self._ntos = ntos\n\n def _handleAnchor(self):\n """\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((0, 0))\n >>> pen.moveTo((10, 10))\n >>> pen._commands\n ['M10 10']\n """\n if self._lastCommand == "M":\n self._commands.pop(-1)\n\n def _moveTo(self, pt):\n """\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((0, 0))\n >>> pen._commands\n ['M0 0']\n\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((10, 0))\n >>> pen._commands\n ['M10 0']\n\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((0, 10))\n >>> pen._commands\n ['M0 10']\n """\n self._handleAnchor()\n t = "M%s" % (pointToString(pt, self._ntos))\n self._commands.append(t)\n self._lastCommand = "M"\n self._lastX, self._lastY = pt\n\n def _lineTo(self, pt):\n """\n # duplicate point\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((10, 10))\n >>> pen.lineTo((10, 10))\n >>> pen._commands\n ['M10 10']\n\n # vertical line\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((10, 10))\n >>> pen.lineTo((10, 0))\n >>> pen._commands\n ['M10 10', 'V0']\n\n # horizontal line\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((10, 10))\n >>> pen.lineTo((0, 10))\n >>> pen._commands\n ['M10 10', 'H0']\n\n # basic\n >>> pen = SVGPathPen(None)\n >>> pen.lineTo((70, 80))\n >>> pen._commands\n ['L70 80']\n\n # basic following a moveto\n >>> pen = SVGPathPen(None)\n >>> pen.moveTo((0, 0))\n >>> pen.lineTo((10, 10))\n >>> pen._commands\n ['M0 0', ' 10 10']\n """\n x, y = pt\n # duplicate point\n if x == self._lastX and y == self._lastY:\n return\n # vertical line\n elif x == self._lastX:\n cmd = "V"\n pts = self._ntos(y)\n # horizontal line\n elif y == self._lastY:\n cmd = "H"\n pts = self._ntos(x)\n # previous was a moveto\n elif self._lastCommand == "M":\n cmd = None\n pts = " " + pointToString(pt, self._ntos)\n # basic\n else:\n cmd = "L"\n pts = pointToString(pt, self._ntos)\n # write the string\n t = ""\n if cmd:\n t += cmd\n self._lastCommand = cmd\n t += pts\n self._commands.append(t)\n # store for future reference\n self._lastX, self._lastY = pt\n\n def _curveToOne(self, pt1, pt2, pt3):\n """\n >>> pen = SVGPathPen(None)\n >>> pen.curveTo((10, 20), (30, 40), (50, 60))\n >>> pen._commands\n ['C10 20 30 40 50 60']\n """\n t = "C"\n t += pointToString(pt1, self._ntos) + " "\n t += pointToString(pt2, self._ntos) + " "\n t += pointToString(pt3, self._ntos)\n self._commands.append(t)\n self._lastCommand = "C"\n self._lastX, self._lastY = pt3\n\n def _qCurveToOne(self, pt1, pt2):\n """\n >>> pen = SVGPathPen(None)\n >>> pen.qCurveTo((10, 20), (30, 40))\n >>> pen._commands\n ['Q10 20 30 40']\n >>> from fontTools.misc.roundTools import otRound\n >>> pen = SVGPathPen(None, ntos=lambda v: str(otRound(v)))\n >>> pen.qCurveTo((3, 3), (7, 5), (11, 4))\n >>> pen._commands\n ['Q3 3 5 4', 'Q7 5 11 4']\n """\n assert pt2 is not None\n t = "Q"\n t += pointToString(pt1, self._ntos) + " "\n t += pointToString(pt2, self._ntos)\n self._commands.append(t)\n self._lastCommand = "Q"\n self._lastX, self._lastY = pt2\n\n def _closePath(self):\n """\n >>> pen = SVGPathPen(None)\n >>> pen.closePath()\n >>> pen._commands\n ['Z']\n """\n self._commands.append("Z")\n self._lastCommand = "Z"\n self._lastX = self._lastY = None\n\n def _endPath(self):\n """\n >>> pen = SVGPathPen(None)\n >>> pen.endPath()\n >>> pen._commands\n []\n """\n self._lastCommand = None\n self._lastX = self._lastY = None\n\n def getCommands(self):\n return "".join(self._commands)\n\n\ndef main(args=None):\n """Generate per-character SVG from font and text"""\n\n if args is None:\n import sys\n\n args = sys.argv[1:]\n\n from fontTools.ttLib import TTFont\n import argparse\n\n parser = argparse.ArgumentParser(\n "fonttools pens.svgPathPen", description="Generate SVG from text"\n )\n parser.add_argument("font", metavar="font.ttf", help="Font file.")\n parser.add_argument("text", metavar="text", nargs="?", help="Text string.")\n parser.add_argument(\n "-y",\n metavar="<number>",\n help="Face index into a collection to open. Zero based.",\n )\n parser.add_argument(\n "--glyphs",\n metavar="whitespace-separated list of glyph names",\n type=str,\n help="Glyphs to show. Exclusive with text option",\n )\n parser.add_argument(\n "--variations",\n metavar="AXIS=LOC",\n default="",\n help="List of space separated locations. A location consist in "\n "the name of a variation axis, followed by '=' and a number. E.g.: "\n "wght=700 wdth=80. The default is the location of the base master.",\n )\n\n options = parser.parse_args(args)\n\n fontNumber = int(options.y) if options.y is not None else 0\n\n font = TTFont(options.font, fontNumber=fontNumber)\n text = options.text\n glyphs = options.glyphs\n\n location = {}\n for tag_v in options.variations.split():\n fields = tag_v.split("=")\n tag = fields[0].strip()\n v = float(fields[1])\n location[tag] = v\n\n hhea = font["hhea"]\n ascent, descent = hhea.ascent, hhea.descent\n\n glyphset = font.getGlyphSet(location=location)\n cmap = font["cmap"].getBestCmap()\n\n if glyphs is not None and text is not None:\n raise ValueError("Options --glyphs and --text are exclusive")\n\n if glyphs is None:\n glyphs = " ".join(cmap[ord(u)] for u in text)\n\n glyphs = glyphs.split()\n\n s = ""\n width = 0\n for g in glyphs:\n glyph = glyphset[g]\n\n pen = SVGPathPen(glyphset)\n glyph.draw(pen)\n commands = pen.getCommands()\n\n s += '<g transform="translate(%d %d) scale(1 -1)"><path d="%s"/></g>\n' % (\n width,\n ascent,\n commands,\n )\n\n width += glyph.width\n\n print('<?xml version="1.0" encoding="UTF-8"?>')\n print(\n '<svg width="%d" height="%d" xmlns="http://www.w3.org/2000/svg">'\n % (width, ascent - descent)\n )\n print(s, end="")\n print("</svg>")\n\n\nif __name__ == "__main__":\n import sys\n\n if len(sys.argv) == 1:\n import doctest\n\n sys.exit(doctest.testmod().failed)\n\n sys.exit(main())\n
.venv\Lib\site-packages\fontTools\pens\svgPathPen.py
svgPathPen.py
Python
8,882
0.95
0.083871
0.045977
vue-tools
88
2024-08-20T09:16:58.643876
BSD-3-Clause
false
b3c45ed56d4ff088299e6076bfa4e520
# Copyright (c) 2009 Type Supply LLC\n# Author: Tal Leming\n\nfrom __future__ import annotations\n\nfrom typing import Any, Dict, List, Tuple\n\nfrom fontTools.cffLib.specializer import commandsToProgram, specializeCommands\nfrom fontTools.misc.psCharStrings import T2CharString\nfrom fontTools.misc.roundTools import otRound, roundFunc\nfrom fontTools.pens.basePen import BasePen\n\n\nclass T2CharStringPen(BasePen):\n """Pen to draw Type 2 CharStrings.\n\n The 'roundTolerance' argument controls the rounding of point coordinates.\n It is defined as the maximum absolute difference between the original\n float and the rounded integer value.\n The default tolerance of 0.5 means that all floats are rounded to integer;\n a value of 0 disables rounding; values in between will only round floats\n which are close to their integral part within the tolerated range.\n """\n\n def __init__(\n self,\n width: float | None,\n glyphSet: Dict[str, Any] | None,\n roundTolerance: float = 0.5,\n CFF2: bool = False,\n ) -> None:\n super(T2CharStringPen, self).__init__(glyphSet)\n self.round = roundFunc(roundTolerance)\n self._CFF2 = CFF2\n self._width = width\n self._commands: List[Tuple[str | bytes, List[float]]] = []\n self._p0 = (0, 0)\n\n def _p(self, pt: Tuple[float, float]) -> List[float]:\n p0 = self._p0\n pt = self._p0 = (self.round(pt[0]), self.round(pt[1]))\n return [pt[0] - p0[0], pt[1] - p0[1]]\n\n def _moveTo(self, pt: Tuple[float, float]) -> None:\n self._commands.append(("rmoveto", self._p(pt)))\n\n def _lineTo(self, pt: Tuple[float, float]) -> None:\n self._commands.append(("rlineto", self._p(pt)))\n\n def _curveToOne(\n self,\n pt1: Tuple[float, float],\n pt2: Tuple[float, float],\n pt3: Tuple[float, float],\n ) -> None:\n _p = self._p\n self._commands.append(("rrcurveto", _p(pt1) + _p(pt2) + _p(pt3)))\n\n def _closePath(self) -> None:\n pass\n\n def _endPath(self) -> None:\n pass\n\n def getCharString(\n self,\n private: Dict | None = None,\n globalSubrs: List | None = None,\n optimize: bool = True,\n ) -> T2CharString:\n commands = self._commands\n if optimize:\n maxstack = 48 if not self._CFF2 else 513\n commands = specializeCommands(\n commands, generalizeFirst=False, maxstack=maxstack\n )\n program = commandsToProgram(commands)\n if self._width is not None:\n assert (\n not self._CFF2\n ), "CFF2 does not allow encoding glyph width in CharString."\n program.insert(0, otRound(self._width))\n if not self._CFF2:\n program.append("endchar")\n charString = T2CharString(\n program=program, private=private, globalSubrs=globalSubrs\n )\n return charString\n
.venv\Lib\site-packages\fontTools\pens\t2CharStringPen.py
t2CharStringPen.py
Python
3,019
0.95
0.147727
0.027027
vue-tools
754
2023-11-02T03:51:10.283103
BSD-3-Clause
false
231d770e822130c3e9b602655ecf2ded
"""Pen multiplexing drawing to one or more pens."""\n\nfrom fontTools.pens.basePen import AbstractPen\n\n\n__all__ = ["TeePen"]\n\n\nclass TeePen(AbstractPen):\n """Pen multiplexing drawing to one or more pens.\n\n Use either as TeePen(pen1, pen2, ...) or TeePen(iterableOfPens)."""\n\n def __init__(self, *pens):\n if len(pens) == 1:\n pens = pens[0]\n self.pens = pens\n\n def moveTo(self, p0):\n for pen in self.pens:\n pen.moveTo(p0)\n\n def lineTo(self, p1):\n for pen in self.pens:\n pen.lineTo(p1)\n\n def qCurveTo(self, *points):\n for pen in self.pens:\n pen.qCurveTo(*points)\n\n def curveTo(self, *points):\n for pen in self.pens:\n pen.curveTo(*points)\n\n def closePath(self):\n for pen in self.pens:\n pen.closePath()\n\n def endPath(self):\n for pen in self.pens:\n pen.endPath()\n\n def addComponent(self, glyphName, transformation):\n for pen in self.pens:\n pen.addComponent(glyphName, transformation)\n\n\nif __name__ == "__main__":\n from fontTools.pens.basePen import _TestPen\n\n pen = TeePen(_TestPen(), _TestPen())\n pen.moveTo((0, 0))\n pen.lineTo((0, 100))\n pen.curveTo((50, 75), (60, 50), (50, 25))\n pen.closePath()\n
.venv\Lib\site-packages\fontTools\pens\teePen.py
teePen.py
Python
1,345
0.85
0.327273
0
python-kit
811
2025-03-31T10:29:53.119405
Apache-2.0
false
d35e6b88b452daee3103544a3dabfd3d
from fontTools.pens.filterPen import FilterPen, FilterPointPen\n\n\n__all__ = ["TransformPen", "TransformPointPen"]\n\n\nclass TransformPen(FilterPen):\n """Pen that transforms all coordinates using a Affine transformation,\n and passes them to another pen.\n """\n\n def __init__(self, outPen, transformation):\n """The 'outPen' argument is another pen object. It will receive the\n transformed coordinates. The 'transformation' argument can either\n be a six-tuple, or a fontTools.misc.transform.Transform object.\n """\n super(TransformPen, self).__init__(outPen)\n if not hasattr(transformation, "transformPoint"):\n from fontTools.misc.transform import Transform\n\n transformation = Transform(*transformation)\n self._transformation = transformation\n self._transformPoint = transformation.transformPoint\n self._stack = []\n\n def moveTo(self, pt):\n self._outPen.moveTo(self._transformPoint(pt))\n\n def lineTo(self, pt):\n self._outPen.lineTo(self._transformPoint(pt))\n\n def curveTo(self, *points):\n self._outPen.curveTo(*self._transformPoints(points))\n\n def qCurveTo(self, *points):\n if points[-1] is None:\n points = self._transformPoints(points[:-1]) + [None]\n else:\n points = self._transformPoints(points)\n self._outPen.qCurveTo(*points)\n\n def _transformPoints(self, points):\n transformPoint = self._transformPoint\n return [transformPoint(pt) for pt in points]\n\n def closePath(self):\n self._outPen.closePath()\n\n def endPath(self):\n self._outPen.endPath()\n\n def addComponent(self, glyphName, transformation):\n transformation = self._transformation.transform(transformation)\n self._outPen.addComponent(glyphName, transformation)\n\n\nclass TransformPointPen(FilterPointPen):\n """PointPen that transforms all coordinates using a Affine transformation,\n and passes them to another PointPen.\n\n For example::\n\n >>> from fontTools.pens.recordingPen import RecordingPointPen\n >>> rec = RecordingPointPen()\n >>> pen = TransformPointPen(rec, (2, 0, 0, 2, -10, 5))\n >>> v = iter(rec.value)\n >>> pen.beginPath(identifier="contour-0")\n >>> next(v)\n ('beginPath', (), {'identifier': 'contour-0'})\n\n >>> pen.addPoint((100, 100), "line")\n >>> next(v)\n ('addPoint', ((190, 205), 'line', False, None), {})\n\n >>> pen.endPath()\n >>> next(v)\n ('endPath', (), {})\n\n >>> pen.addComponent("a", (1, 0, 0, 1, -10, 5), identifier="component-0")\n >>> next(v)\n ('addComponent', ('a', <Transform [2 0 0 2 -30 15]>), {'identifier': 'component-0'})\n """\n\n def __init__(self, outPointPen, transformation):\n """The 'outPointPen' argument is another point pen object.\n It will receive the transformed coordinates.\n The 'transformation' argument can either be a six-tuple, or a\n fontTools.misc.transform.Transform object.\n """\n super().__init__(outPointPen)\n if not hasattr(transformation, "transformPoint"):\n from fontTools.misc.transform import Transform\n\n transformation = Transform(*transformation)\n self._transformation = transformation\n self._transformPoint = transformation.transformPoint\n\n def addPoint(self, pt, segmentType=None, smooth=False, name=None, **kwargs):\n self._outPen.addPoint(\n self._transformPoint(pt), segmentType, smooth, name, **kwargs\n )\n\n def addComponent(self, baseGlyphName, transformation, **kwargs):\n transformation = self._transformation.transform(transformation)\n self._outPen.addComponent(baseGlyphName, transformation, **kwargs)\n\n\nif __name__ == "__main__":\n from fontTools.pens.basePen import _TestPen\n\n pen = TransformPen(_TestPen(None), (2, 0, 0.5, 2, -10, 0))\n pen.moveTo((0, 0))\n pen.lineTo((0, 100))\n pen.curveTo((50, 75), (60, 50), (50, 25), (0, 0))\n pen.closePath()\n
.venv\Lib\site-packages\fontTools\pens\transformPen.py
transformPen.py
Python
4,171
0.85
0.165217
0
react-lib
555
2023-10-07T09:55:56.442802
GPL-3.0
false
0b3a9b293e7eb6f028e4fce76d7f1985
from array import array\nfrom typing import Any, Callable, Dict, Optional, Tuple\nfrom fontTools.misc.fixedTools import MAX_F2DOT14, floatToFixedToFloat\nfrom fontTools.misc.loggingTools import LogMixin\nfrom fontTools.pens.pointPen import AbstractPointPen\nfrom fontTools.misc.roundTools import otRound\nfrom fontTools.pens.basePen import LoggingPen, PenError\nfrom fontTools.pens.transformPen import TransformPen, TransformPointPen\nfrom fontTools.ttLib.tables import ttProgram\nfrom fontTools.ttLib.tables._g_l_y_f import flagOnCurve, flagCubic\nfrom fontTools.ttLib.tables._g_l_y_f import Glyph\nfrom fontTools.ttLib.tables._g_l_y_f import GlyphComponent\nfrom fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates\nfrom fontTools.ttLib.tables._g_l_y_f import dropImpliedOnCurvePoints\nimport math\n\n\n__all__ = ["TTGlyphPen", "TTGlyphPointPen"]\n\n\nclass _TTGlyphBasePen:\n def __init__(\n self,\n glyphSet: Optional[Dict[str, Any]],\n handleOverflowingTransforms: bool = True,\n ) -> None:\n """\n Construct a new pen.\n\n Args:\n glyphSet (Dict[str, Any]): A glyphset object, used to resolve components.\n handleOverflowingTransforms (bool): See below.\n\n If ``handleOverflowingTransforms`` is True, the components' transform values\n are checked that they don't overflow the limits of a F2Dot14 number:\n -2.0 <= v < +2.0. If any transform value exceeds these, the composite\n glyph is decomposed.\n\n An exception to this rule is done for values that are very close to +2.0\n (both for consistency with the -2.0 case, and for the relative frequency\n these occur in real fonts). When almost +2.0 values occur (and all other\n values are within the range -2.0 <= x <= +2.0), they are clamped to the\n maximum positive value that can still be encoded as an F2Dot14: i.e.\n 1.99993896484375.\n\n If False, no check is done and all components are translated unmodified\n into the glyf table, followed by an inevitable ``struct.error`` once an\n attempt is made to compile them.\n\n If both contours and components are present in a glyph, the components\n are decomposed.\n """\n self.glyphSet = glyphSet\n self.handleOverflowingTransforms = handleOverflowingTransforms\n self.init()\n\n def _decompose(\n self,\n glyphName: str,\n transformation: Tuple[float, float, float, float, float, float],\n ):\n tpen = self.transformPen(self, transformation)\n getattr(self.glyphSet[glyphName], self.drawMethod)(tpen)\n\n def _isClosed(self):\n """\n Check if the current path is closed.\n """\n raise NotImplementedError\n\n def init(self) -> None:\n self.points = []\n self.endPts = []\n self.types = []\n self.components = []\n\n def addComponent(\n self,\n baseGlyphName: str,\n transformation: Tuple[float, float, float, float, float, float],\n identifier: Optional[str] = None,\n **kwargs: Any,\n ) -> None:\n """\n Add a sub glyph.\n """\n self.components.append((baseGlyphName, transformation))\n\n def _buildComponents(self, componentFlags):\n if self.handleOverflowingTransforms:\n # we can't encode transform values > 2 or < -2 in F2Dot14,\n # so we must decompose the glyph if any transform exceeds these\n overflowing = any(\n s > 2 or s < -2\n for (glyphName, transformation) in self.components\n for s in transformation[:4]\n )\n components = []\n for glyphName, transformation in self.components:\n if glyphName not in self.glyphSet:\n self.log.warning(f"skipped non-existing component '{glyphName}'")\n continue\n if self.points or (self.handleOverflowingTransforms and overflowing):\n # can't have both coordinates and components, so decompose\n self._decompose(glyphName, transformation)\n continue\n\n component = GlyphComponent()\n component.glyphName = glyphName\n component.x, component.y = (otRound(v) for v in transformation[4:])\n # quantize floats to F2Dot14 so we get same values as when decompiled\n # from a binary glyf table\n transformation = tuple(\n floatToFixedToFloat(v, 14) for v in transformation[:4]\n )\n if transformation != (1, 0, 0, 1):\n if self.handleOverflowingTransforms and any(\n MAX_F2DOT14 < s <= 2 for s in transformation\n ):\n # clamp values ~= +2.0 so we can keep the component\n transformation = tuple(\n MAX_F2DOT14 if MAX_F2DOT14 < s <= 2 else s\n for s in transformation\n )\n component.transform = (transformation[:2], transformation[2:])\n component.flags = componentFlags\n components.append(component)\n return components\n\n def glyph(\n self,\n componentFlags: int = 0x04,\n dropImpliedOnCurves: bool = False,\n *,\n round: Callable[[float], int] = otRound,\n ) -> Glyph:\n """\n Returns a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.\n\n Args:\n componentFlags: Flags to use for component glyphs. (default: 0x04)\n\n dropImpliedOnCurves: Whether to remove implied-oncurve points. (default: False)\n """\n if not self._isClosed():\n raise PenError("Didn't close last contour.")\n components = self._buildComponents(componentFlags)\n\n glyph = Glyph()\n glyph.coordinates = GlyphCoordinates(self.points)\n glyph.endPtsOfContours = self.endPts\n glyph.flags = array("B", self.types)\n self.init()\n\n if components:\n # If both components and contours were present, they have by now\n # been decomposed by _buildComponents.\n glyph.components = components\n glyph.numberOfContours = -1\n else:\n glyph.numberOfContours = len(glyph.endPtsOfContours)\n glyph.program = ttProgram.Program()\n glyph.program.fromBytecode(b"")\n if dropImpliedOnCurves:\n dropImpliedOnCurvePoints(glyph)\n glyph.coordinates.toInt(round=round)\n\n return glyph\n\n\nclass TTGlyphPen(_TTGlyphBasePen, LoggingPen):\n """\n Pen used for drawing to a TrueType glyph.\n\n This pen can be used to construct or modify glyphs in a TrueType format\n font. After using the pen to draw, use the ``.glyph()`` method to retrieve\n a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.\n """\n\n drawMethod = "draw"\n transformPen = TransformPen\n\n def __init__(\n self,\n glyphSet: Optional[Dict[str, Any]] = None,\n handleOverflowingTransforms: bool = True,\n outputImpliedClosingLine: bool = False,\n ) -> None:\n super().__init__(glyphSet, handleOverflowingTransforms)\n self.outputImpliedClosingLine = outputImpliedClosingLine\n\n def _addPoint(self, pt: Tuple[float, float], tp: int) -> None:\n self.points.append(pt)\n self.types.append(tp)\n\n def _popPoint(self) -> None:\n self.points.pop()\n self.types.pop()\n\n def _isClosed(self) -> bool:\n return (not self.points) or (\n self.endPts and self.endPts[-1] == len(self.points) - 1\n )\n\n def lineTo(self, pt: Tuple[float, float]) -> None:\n self._addPoint(pt, flagOnCurve)\n\n def moveTo(self, pt: Tuple[float, float]) -> None:\n if not self._isClosed():\n raise PenError('"move"-type point must begin a new contour.')\n self._addPoint(pt, flagOnCurve)\n\n def curveTo(self, *points) -> None:\n assert len(points) % 2 == 1\n for pt in points[:-1]:\n self._addPoint(pt, flagCubic)\n\n # last point is None if there are no on-curve points\n if points[-1] is not None:\n self._addPoint(points[-1], 1)\n\n def qCurveTo(self, *points) -> None:\n assert len(points) >= 1\n for pt in points[:-1]:\n self._addPoint(pt, 0)\n\n # last point is None if there are no on-curve points\n if points[-1] is not None:\n self._addPoint(points[-1], 1)\n\n def closePath(self) -> None:\n endPt = len(self.points) - 1\n\n # ignore anchors (one-point paths)\n if endPt == 0 or (self.endPts and endPt == self.endPts[-1] + 1):\n self._popPoint()\n return\n\n if not self.outputImpliedClosingLine:\n # if first and last point on this path are the same, remove last\n startPt = 0\n if self.endPts:\n startPt = self.endPts[-1] + 1\n if self.points[startPt] == self.points[endPt]:\n self._popPoint()\n endPt -= 1\n\n self.endPts.append(endPt)\n\n def endPath(self) -> None:\n # TrueType contours are always "closed"\n self.closePath()\n\n\nclass TTGlyphPointPen(_TTGlyphBasePen, LogMixin, AbstractPointPen):\n """\n Point pen used for drawing to a TrueType glyph.\n\n This pen can be used to construct or modify glyphs in a TrueType format\n font. After using the pen to draw, use the ``.glyph()`` method to retrieve\n a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.\n """\n\n drawMethod = "drawPoints"\n transformPen = TransformPointPen\n\n def init(self) -> None:\n super().init()\n self._currentContourStartIndex = None\n\n def _isClosed(self) -> bool:\n return self._currentContourStartIndex is None\n\n def beginPath(self, identifier: Optional[str] = None, **kwargs: Any) -> None:\n """\n Start a new sub path.\n """\n if not self._isClosed():\n raise PenError("Didn't close previous contour.")\n self._currentContourStartIndex = len(self.points)\n\n def endPath(self) -> None:\n """\n End the current sub path.\n """\n # TrueType contours are always "closed"\n if self._isClosed():\n raise PenError("Contour is already closed.")\n if self._currentContourStartIndex == len(self.points):\n # ignore empty contours\n self._currentContourStartIndex = None\n return\n\n contourStart = self.endPts[-1] + 1 if self.endPts else 0\n self.endPts.append(len(self.points) - 1)\n self._currentContourStartIndex = None\n\n # Resolve types for any cubic segments\n flags = self.types\n for i in range(contourStart, len(flags)):\n if flags[i] == "curve":\n j = i - 1\n if j < contourStart:\n j = len(flags) - 1\n while flags[j] == 0:\n flags[j] = flagCubic\n j -= 1\n flags[i] = flagOnCurve\n\n def addPoint(\n self,\n pt: Tuple[float, float],\n segmentType: Optional[str] = None,\n smooth: bool = False,\n name: Optional[str] = None,\n identifier: Optional[str] = None,\n **kwargs: Any,\n ) -> None:\n """\n Add a point to the current sub path.\n """\n if self._isClosed():\n raise PenError("Can't add a point to a closed contour.")\n if segmentType is None:\n self.types.append(0)\n elif segmentType in ("line", "move"):\n self.types.append(flagOnCurve)\n elif segmentType == "qcurve":\n self.types.append(flagOnCurve)\n elif segmentType == "curve":\n self.types.append("curve")\n else:\n raise AssertionError(segmentType)\n\n self.points.append(pt)\n
.venv\Lib\site-packages\fontTools\pens\ttGlyphPen.py
ttGlyphPen.py
Python
12,205
0.95
0.223881
0.067138
awesome-app
980
2025-03-26T18:25:41.774898
Apache-2.0
false
c2646261e1154ef2f7356db4f171e138
from fontTools.pens.basePen import BasePen\n\n\n__all__ = ["WxPen"]\n\n\nclass WxPen(BasePen):\n def __init__(self, glyphSet, path=None):\n BasePen.__init__(self, glyphSet)\n if path is None:\n import wx\n\n path = wx.GraphicsRenderer.GetDefaultRenderer().CreatePath()\n self.path = path\n\n def _moveTo(self, p):\n self.path.MoveToPoint(*p)\n\n def _lineTo(self, p):\n self.path.AddLineToPoint(*p)\n\n def _curveToOne(self, p1, p2, p3):\n self.path.AddCurveToPoint(*p1 + p2 + p3)\n\n def _qCurveToOne(self, p1, p2):\n self.path.AddQuadCurveToPoint(*p1 + p2)\n\n def _closePath(self):\n self.path.CloseSubpath()\n
.venv\Lib\site-packages\fontTools\pens\wxPen.py
wxPen.py
Python
709
0.85
0.275862
0
awesome-app
854
2024-03-11T14:47:22.545368
GPL-3.0
false
93f7b33ec4b094c8dd65fc7110f5807d
"""Empty __init__.py file to signal Python this directory is a package."""\n
.venv\Lib\site-packages\fontTools\pens\__init__.py
__init__.py
Python
76
0.5
0
0
python-kit
581
2024-07-26T21:20:38.666037
Apache-2.0
false
6d412be7408e8f32685229b58fb23583
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\areaPen.cpython-313.pyc
areaPen.cpython-313.pyc
Other
2,956
0.8
0
0
python-kit
119
2024-05-16T06:36:21.987560
GPL-3.0
false
4926f2e815fe27eed9fcb4e7e70dbe7f
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\basePen.cpython-313.pyc
basePen.cpython-313.pyc
Other
19,913
0.95
0.109804
0
react-lib
428
2025-05-21T16:49:26.180866
GPL-3.0
false
a3fcfd497e8202b8f94690510566e716
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\boundsPen.cpython-313.pyc
boundsPen.cpython-313.pyc
Other
4,712
0.8
0.025641
0
vue-tools
765
2023-08-07T19:01:48.269307
BSD-3-Clause
false
fded4fce6b98dbca49a3ed9dcce74baf
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\cairoPen.cpython-313.pyc
cairoPen.cpython-313.pyc
Other
1,640
0.7
0
0
python-kit
709
2024-08-20T14:17:55.453063
MIT
false
0457f3caac58fcca1fb07637c3efd695
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\cocoaPen.cpython-313.pyc
cocoaPen.cpython-313.pyc
Other
1,717
0.8
0
0
python-kit
366
2023-12-12T06:00:24.684871
GPL-3.0
false
dabafd9e83ed414a0e53c12187ebe90e
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\cu2quPen.cpython-313.pyc
cu2quPen.cpython-313.pyc
Other
15,000
0.95
0.053333
0.014925
awesome-app
753
2024-04-26T19:33:32.215227
GPL-3.0
false
c717ccf8bee1e775242ee3b283241f0f
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\explicitClosingLinePen.cpython-313.pyc
explicitClosingLinePen.cpython-313.pyc
Other
3,464
0.95
0.011236
0
react-lib
374
2024-10-04T16:45:31.511165
MIT
false
f48b4b7234026712a7b8bac52942c660
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\filterPen.cpython-313.pyc
filterPen.cpython-313.pyc
Other
10,676
0.95
0.039216
0
vue-tools
546
2024-12-23T11:31:59.214459
MIT
false
6ddc1a7cdfae4d9ea0e22f594d92dc57
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\freetypePen.cpython-313.pyc
freetypePen.cpython-313.pyc
Other
22,410
0.95
0.06469
0.009091
react-lib
762
2024-12-27T12:14:56.168736
Apache-2.0
false
56e9756cf0d1ad4f225e9ba7f4cd0c5d
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\hashPointPen.cpython-313.pyc
hashPointPen.cpython-313.pyc
Other
4,795
0.95
0.098592
0
vue-tools
899
2024-07-26T08:52:51.827420
GPL-3.0
false
9c25a2175fb5b06c634b2f6d99080ac2
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\momentsPen.cpython-313.pyc
momentsPen.cpython-313.pyc
Other
39,217
0.8
0
0.008681
python-kit
399
2024-08-26T12:59:24.457735
GPL-3.0
false
8265dc71e4ab64c6d099b256f6181e96
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\perimeterPen.cpython-313.pyc
perimeterPen.cpython-313.pyc
Other
4,060
0.8
0
0
react-lib
450
2025-01-10T06:57:30.198368
Apache-2.0
false
ef7a89af8cd56c3d06f3f7fb801d4cd3
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\pointInsidePen.cpython-313.pyc
pointInsidePen.cpython-313.pyc
Other
7,058
0.95
0.06383
0
awesome-app
852
2024-01-10T21:06:15.062910
MIT
false
7b0e796a589af023dce3b1b23e0c487c
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\pointPen.cpython-313.pyc
pointPen.cpython-313.pyc
Other
23,776
0.95
0.069565
0
awesome-app
46
2023-07-24T23:12:56.541435
GPL-3.0
false
cd598cace752b9f265f8ba79ace666d0
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\qtPen.cpython-313.pyc
qtPen.cpython-313.pyc
Other
1,863
0.8
0
0
python-kit
155
2024-10-11T16:54:46.636474
Apache-2.0
false
8b6d22b3fa7f2fd720ede97cefd2372c
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\qu2cuPen.cpython-313.pyc
qu2cuPen.cpython-313.pyc
Other
4,058
0.8
0.021739
0
awesome-app
651
2025-06-20T07:50:40.603540
BSD-3-Clause
false
80986ae425b176aa2e0cdc88f8497280
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\quartzPen.cpython-313.pyc
quartzPen.cpython-313.pyc
Other
2,500
0.8
0
0
react-lib
11
2025-03-31T09:42:22.958072
GPL-3.0
false
ea83eb5e87f9d476d35b97ff01f9abba
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\recordingPen.cpython-313.pyc
recordingPen.cpython-313.pyc
Other
14,704
0.95
0.084615
0
python-kit
608
2024-04-10T14:46:59.508302
Apache-2.0
false
bdbd9ff45035588bb467db12aa1277cd
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\reportLabPen.cpython-313.pyc
reportLabPen.cpython-313.pyc
Other
3,605
0.8
0.027778
0
python-kit
184
2025-03-27T18:05:24.323068
BSD-3-Clause
false
903846540cccad9bcef9a92cb717250b
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\reverseContourPen.cpython-313.pyc
reverseContourPen.cpython-313.pyc
Other
3,475
0.8
0
0
react-lib
37
2025-01-21T22:41:18.899943
GPL-3.0
false
d204b5538257691cc71c48162efb9011
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\roundingPen.cpython-313.pyc
roundingPen.cpython-313.pyc
Other
6,616
0.95
0.019048
0
react-lib
125
2023-09-15T02:57:38.592689
GPL-3.0
false
2a75da277e9b6fab0e29681f5d097a7a
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\statisticsPen.cpython-313.pyc
statisticsPen.cpython-313.pyc
Other
13,667
0.8
0.024691
0.012739
node-utils
871
2023-09-30T10:19:01.268511
GPL-3.0
false
8c2c2d97251cb1469afbdf8be41a917c
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\svgPathPen.cpython-313.pyc
svgPathPen.cpython-313.pyc
Other
11,154
0.95
0
0.033816
python-kit
541
2024-04-02T11:06:39.722641
Apache-2.0
false
a4d8d7a39813e533e145e1e92d66483b
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\t2CharStringPen.cpython-313.pyc
t2CharStringPen.cpython-313.pyc
Other
4,728
0.8
0
0
awesome-app
17
2023-12-16T22:47:19.952931
BSD-3-Clause
false
b9e5af354f49d0c2492915fa808eefb5
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\teePen.cpython-313.pyc
teePen.cpython-313.pyc
Other
2,897
0.8
0
0
node-utils
771
2025-06-19T03:51:53.283390
MIT
false
de8b1c01a12677a073c1255ca4e17ba2
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\transformPen.cpython-313.pyc
transformPen.cpython-313.pyc
Other
6,250
0.95
0
0
react-lib
608
2024-02-01T02:33:45.067958
Apache-2.0
false
a6b8692abbc000554fc24d63ce4cd2d5
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\ttGlyphPen.cpython-313.pyc
ttGlyphPen.cpython-313.pyc
Other
16,159
0.8
0.060606
0.006803
node-utils
264
2024-09-07T07:21:57.823980
BSD-3-Clause
false
b609a7eccee53b7dee7fef2f3ec674f6
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\wxPen.cpython-313.pyc
wxPen.cpython-313.pyc
Other
1,998
0.8
0
0
react-lib
426
2024-03-27T14:18:55.972927
MIT
false
5e8dfa6b8a950befafbe44a3c52f2f9e
\n\n
.venv\Lib\site-packages\fontTools\pens\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
272
0.7
0
0
react-lib
982
2024-12-18T09:34:20.478209
MIT
false
19875c298531ca66d0e24e5df32bb30f
"""Benchmark the qu2cu algorithm performance."""\n\nfrom .qu2cu import *\nfrom fontTools.cu2qu import curve_to_quadratic\nimport random\nimport timeit\n\nMAX_ERR = 0.5\nNUM_CURVES = 5\n\n\ndef generate_curves(n):\n points = [\n tuple(float(random.randint(0, 2048)) for coord in range(2))\n for point in range(1 + 3 * n)\n ]\n curves = []\n for i in range(n):\n curves.append(tuple(points[i * 3 : i * 3 + 4]))\n return curves\n\n\ndef setup_quadratic_to_curves():\n curves = generate_curves(NUM_CURVES)\n quadratics = [curve_to_quadratic(curve, MAX_ERR) for curve in curves]\n return quadratics, MAX_ERR\n\n\ndef run_benchmark(module, function, setup_suffix="", repeat=25, number=1):\n setup_func = "setup_" + function\n if setup_suffix:\n print("%s with %s:" % (function, setup_suffix), end="")\n setup_func += "_" + setup_suffix\n else:\n print("%s:" % function, end="")\n\n def wrapper(function, setup_func):\n function = globals()[function]\n setup_func = globals()[setup_func]\n\n def wrapped():\n return function(*setup_func())\n\n return wrapped\n\n results = timeit.repeat(wrapper(function, setup_func), repeat=repeat, number=number)\n print("\t%5.1fus" % (min(results) * 1000000.0 / number))\n\n\ndef main():\n run_benchmark("qu2cu", "quadratic_to_curves")\n\n\nif __name__ == "__main__":\n random.seed(1)\n main()\n
.venv\Lib\site-packages\fontTools\qu2cu\benchmark.py
benchmark.py
Python
1,456
0.85
0.375
0
awesome-app
413
2024-12-27T09:50:34.814046
BSD-3-Clause
false
940c5620eb989830f817363530fd7f2a
import os\nimport argparse\nimport logging\nfrom fontTools.misc.cliTools import makeOutputFileName\nfrom fontTools.ttLib import TTFont\nfrom fontTools.pens.qu2cuPen import Qu2CuPen\nfrom fontTools.pens.ttGlyphPen import TTGlyphPen\nimport fontTools\n\n\nlogger = logging.getLogger("fontTools.qu2cu")\n\n\ndef _font_to_cubic(input_path, output_path=None, **kwargs):\n font = TTFont(input_path)\n logger.info("Converting curves for %s", input_path)\n\n stats = {} if kwargs["dump_stats"] else None\n qu2cu_kwargs = {\n "stats": stats,\n "max_err": kwargs["max_err_em"] * font["head"].unitsPerEm,\n "all_cubic": kwargs["all_cubic"],\n }\n\n assert "gvar" not in font, "Cannot convert variable font"\n glyphSet = font.getGlyphSet()\n glyphOrder = font.getGlyphOrder()\n glyf = font["glyf"]\n for glyphName in glyphOrder:\n glyph = glyphSet[glyphName]\n ttpen = TTGlyphPen(glyphSet)\n pen = Qu2CuPen(ttpen, **qu2cu_kwargs)\n glyph.draw(pen)\n glyf[glyphName] = ttpen.glyph(dropImpliedOnCurves=True)\n\n font["head"].glyphDataFormat = 1\n\n if kwargs["dump_stats"]:\n logger.info("Stats: %s", stats)\n\n logger.info("Saving %s", output_path)\n font.save(output_path)\n\n\ndef _main(args=None):\n """Convert an OpenType font from quadratic to cubic curves"""\n parser = argparse.ArgumentParser(prog="qu2cu")\n parser.add_argument("--version", action="version", version=fontTools.__version__)\n parser.add_argument(\n "infiles",\n nargs="+",\n metavar="INPUT",\n help="one or more input TTF source file(s).",\n )\n parser.add_argument("-v", "--verbose", action="count", default=0)\n parser.add_argument(\n "-e",\n "--conversion-error",\n type=float,\n metavar="ERROR",\n default=0.001,\n help="maxiumum approximation error measured in EM (default: 0.001)",\n )\n parser.add_argument(\n "-c",\n "--all-cubic",\n default=False,\n action="store_true",\n help="whether to only use cubic curves",\n )\n\n output_parser = parser.add_mutually_exclusive_group()\n output_parser.add_argument(\n "-o",\n "--output-file",\n default=None,\n metavar="OUTPUT",\n help=("output filename for the converted TTF."),\n )\n output_parser.add_argument(\n "-d",\n "--output-dir",\n default=None,\n metavar="DIRECTORY",\n help="output directory where to save converted TTFs",\n )\n\n options = parser.parse_args(args)\n\n if not options.verbose:\n level = "WARNING"\n elif options.verbose == 1:\n level = "INFO"\n else:\n level = "DEBUG"\n logging.basicConfig(level=level)\n\n if len(options.infiles) > 1 and options.output_file:\n parser.error("-o/--output-file can't be used with multile inputs")\n\n if options.output_dir:\n output_dir = options.output_dir\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n elif not os.path.isdir(output_dir):\n parser.error("'%s' is not a directory" % output_dir)\n output_paths = [\n os.path.join(output_dir, os.path.basename(p)) for p in options.infiles\n ]\n elif options.output_file:\n output_paths = [options.output_file]\n else:\n output_paths = [\n makeOutputFileName(p, overWrite=True, suffix=".cubic")\n for p in options.infiles\n ]\n\n kwargs = dict(\n dump_stats=options.verbose > 0,\n max_err_em=options.conversion_error,\n all_cubic=options.all_cubic,\n )\n\n for input_path, output_path in zip(options.infiles, output_paths):\n _font_to_cubic(input_path, output_path, **kwargs)\n
.venv\Lib\site-packages\fontTools\qu2cu\cli.py
cli.py
Python
3,839
0.85
0.112
0
react-lib
342
2023-08-16T10:17:41.254884
Apache-2.0
false
d8a4098eb054621ac47c9a98e32b9f5a
MZ
.venv\Lib\site-packages\fontTools\qu2cu\qu2cu.cp313-win_amd64.pyd
qu2cu.cp313-win_amd64.pyd
Other
107,008
0.75
0.017931
0.005658
node-utils
81
2025-02-14T06:09:47.499943
BSD-3-Clause
false
bbd31fe028e668a4df4561d36949ede6
# cython: language_level=3\n# distutils: define_macros=CYTHON_TRACE_NOGIL=1\n\n# Copyright 2023 Google Inc. All Rights Reserved.\n# Copyright 2023 Behdad Esfahbod. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ntry:\n import cython\nexcept (AttributeError, ImportError):\n # if cython not installed, use mock module with no-op decorators and types\n from fontTools.misc import cython\nCOMPILED = cython.compiled\n\nfrom fontTools.misc.bezierTools import splitCubicAtTC\nfrom collections import namedtuple\nimport math\nfrom typing import (\n List,\n Tuple,\n Union,\n)\n\n\n__all__ = ["quadratic_to_curves"]\n\n\n# Copied from cu2qu\n@cython.cfunc\n@cython.returns(cython.int)\n@cython.locals(\n tolerance=cython.double,\n p0=cython.complex,\n p1=cython.complex,\n p2=cython.complex,\n p3=cython.complex,\n)\n@cython.locals(mid=cython.complex, deriv3=cython.complex)\ndef cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):\n """Check if a cubic Bezier lies within a given distance of the origin.\n\n "Origin" means *the* origin (0,0), not the start of the curve. Note that no\n checks are made on the start and end positions of the curve; this function\n only checks the inside of the curve.\n\n Args:\n p0 (complex): Start point of curve.\n p1 (complex): First handle of curve.\n p2 (complex): Second handle of curve.\n p3 (complex): End point of curve.\n tolerance (double): Distance from origin.\n\n Returns:\n bool: True if the cubic Bezier ``p`` entirely lies within a distance\n ``tolerance`` of the origin, False otherwise.\n """\n # First check p2 then p1, as p2 has higher error early on.\n if abs(p2) <= tolerance and abs(p1) <= tolerance:\n return True\n\n # Split.\n mid = (p0 + 3 * (p1 + p2) + p3) * 0.125\n if abs(mid) > tolerance:\n return False\n deriv3 = (p3 + p2 - p1 - p0) * 0.125\n return cubic_farthest_fit_inside(\n p0, (p0 + p1) * 0.5, mid - deriv3, mid, tolerance\n ) and cubic_farthest_fit_inside(mid, mid + deriv3, (p2 + p3) * 0.5, p3, tolerance)\n\n\n@cython.locals(\n p0=cython.complex,\n p1=cython.complex,\n p2=cython.complex,\n p1_2_3=cython.complex,\n)\ndef elevate_quadratic(p0, p1, p2):\n """Given a quadratic bezier curve, return its degree-elevated cubic."""\n\n # https://pomax.github.io/bezierinfo/#reordering\n p1_2_3 = p1 * (2 / 3)\n return (\n p0,\n (p0 * (1 / 3) + p1_2_3),\n (p2 * (1 / 3) + p1_2_3),\n p2,\n )\n\n\n@cython.cfunc\n@cython.locals(\n start=cython.int,\n n=cython.int,\n k=cython.int,\n prod_ratio=cython.double,\n sum_ratio=cython.double,\n ratio=cython.double,\n t=cython.double,\n p0=cython.complex,\n p1=cython.complex,\n p2=cython.complex,\n p3=cython.complex,\n)\ndef merge_curves(curves, start, n):\n """Give a cubic-Bezier spline, reconstruct one cubic-Bezier\n that has the same endpoints and tangents and approxmates\n the spline."""\n\n # Reconstruct the t values of the cut segments\n prod_ratio = 1.0\n sum_ratio = 1.0\n ts = [1]\n for k in range(1, n):\n ck = curves[start + k]\n c_before = curves[start + k - 1]\n\n # |t_(k+1) - t_k| / |t_k - t_(k - 1)| = ratio\n assert ck[0] == c_before[3]\n ratio = abs(ck[1] - ck[0]) / abs(c_before[3] - c_before[2])\n\n prod_ratio *= ratio\n sum_ratio += prod_ratio\n ts.append(sum_ratio)\n\n # (t(n) - t(n - 1)) / (t_(1) - t(0)) = prod_ratio\n\n ts = [t / sum_ratio for t in ts[:-1]]\n\n p0 = curves[start][0]\n p1 = curves[start][1]\n p2 = curves[start + n - 1][2]\n p3 = curves[start + n - 1][3]\n\n # Build the curve by scaling the control-points.\n p1 = p0 + (p1 - p0) / (ts[0] if ts else 1)\n p2 = p3 + (p2 - p3) / ((1 - ts[-1]) if ts else 1)\n\n curve = (p0, p1, p2, p3)\n\n return curve, ts\n\n\n@cython.locals(\n count=cython.int,\n num_offcurves=cython.int,\n i=cython.int,\n off1=cython.complex,\n off2=cython.complex,\n on=cython.complex,\n)\ndef add_implicit_on_curves(p):\n q = list(p)\n count = 0\n num_offcurves = len(p) - 2\n for i in range(1, num_offcurves):\n off1 = p[i]\n off2 = p[i + 1]\n on = off1 + (off2 - off1) * 0.5\n q.insert(i + 1 + count, on)\n count += 1\n return q\n\n\nPoint = Union[Tuple[float, float], complex]\n\n\n@cython.locals(\n cost=cython.int,\n is_complex=cython.int,\n)\ndef quadratic_to_curves(\n quads: List[List[Point]],\n max_err: float = 0.5,\n all_cubic: bool = False,\n) -> List[Tuple[Point, ...]]:\n """Converts a connecting list of quadratic splines to a list of quadratic\n and cubic curves.\n\n A quadratic spline is specified as a list of points. Either each point is\n a 2-tuple of X,Y coordinates, or each point is a complex number with\n real/imaginary components representing X,Y coordinates.\n\n The first and last points are on-curve points and the rest are off-curve\n points, with an implied on-curve point in the middle between every two\n consequtive off-curve points.\n\n Returns:\n The output is a list of tuples of points. Points are represented\n in the same format as the input, either as 2-tuples or complex numbers.\n\n Each tuple is either of length three, for a quadratic curve, or four,\n for a cubic curve. Each curve's last point is the same as the next\n curve's first point.\n\n Args:\n quads: quadratic splines\n\n max_err: absolute error tolerance; defaults to 0.5\n\n all_cubic: if True, only cubic curves are generated; defaults to False\n """\n is_complex = type(quads[0][0]) is complex\n if not is_complex:\n quads = [[complex(x, y) for (x, y) in p] for p in quads]\n\n q = [quads[0][0]]\n costs = [1]\n cost = 1\n for p in quads:\n assert q[-1] == p[0]\n for i in range(len(p) - 2):\n cost += 1\n costs.append(cost)\n costs.append(cost)\n qq = add_implicit_on_curves(p)[1:]\n costs.pop()\n q.extend(qq)\n cost += 1\n costs.append(cost)\n\n curves = spline_to_curves(q, costs, max_err, all_cubic)\n\n if not is_complex:\n curves = [tuple((c.real, c.imag) for c in curve) for curve in curves]\n return curves\n\n\nSolution = namedtuple("Solution", ["num_points", "error", "start_index", "is_cubic"])\n\n\n@cython.locals(\n i=cython.int,\n j=cython.int,\n k=cython.int,\n start=cython.int,\n i_sol_count=cython.int,\n j_sol_count=cython.int,\n this_sol_count=cython.int,\n tolerance=cython.double,\n err=cython.double,\n error=cython.double,\n i_sol_error=cython.double,\n j_sol_error=cython.double,\n all_cubic=cython.int,\n is_cubic=cython.int,\n count=cython.int,\n p0=cython.complex,\n p1=cython.complex,\n p2=cython.complex,\n p3=cython.complex,\n v=cython.complex,\n u=cython.complex,\n)\ndef spline_to_curves(q, costs, tolerance=0.5, all_cubic=False):\n """\n q: quadratic spline with alternating on-curve / off-curve points.\n\n costs: cumulative list of encoding cost of q in terms of number of\n points that need to be encoded. Implied on-curve points do not\n contribute to the cost. If all points need to be encoded, then\n costs will be range(1, len(q)+1).\n """\n\n assert len(q) >= 3, "quadratic spline requires at least 3 points"\n\n # Elevate quadratic segments to cubic\n elevated_quadratics = [\n elevate_quadratic(*q[i : i + 3]) for i in range(0, len(q) - 2, 2)\n ]\n\n # Find sharp corners; they have to be oncurves for sure.\n forced = set()\n for i in range(1, len(elevated_quadratics)):\n p0 = elevated_quadratics[i - 1][2]\n p1 = elevated_quadratics[i][0]\n p2 = elevated_quadratics[i][1]\n if abs(p1 - p0) + abs(p2 - p1) > tolerance + abs(p2 - p0):\n forced.add(i)\n\n # Dynamic-Programming to find the solution with fewest number of\n # cubic curves, and within those the one with smallest error.\n sols = [Solution(0, 0, 0, False)]\n impossible = Solution(len(elevated_quadratics) * 3 + 1, 0, 1, False)\n start = 0\n for i in range(1, len(elevated_quadratics) + 1):\n best_sol = impossible\n for j in range(start, i):\n j_sol_count, j_sol_error = sols[j].num_points, sols[j].error\n\n if not all_cubic:\n # Solution with quadratics between j:i\n this_count = costs[2 * i - 1] - costs[2 * j] + 1\n i_sol_count = j_sol_count + this_count\n i_sol_error = j_sol_error\n i_sol = Solution(i_sol_count, i_sol_error, i - j, False)\n if i_sol < best_sol:\n best_sol = i_sol\n\n if this_count <= 3:\n # Can't get any better than this in the path below\n continue\n\n # Fit elevated_quadratics[j:i] into one cubic\n try:\n curve, ts = merge_curves(elevated_quadratics, j, i - j)\n except ZeroDivisionError:\n continue\n\n # Now reconstruct the segments from the fitted curve\n reconstructed_iter = splitCubicAtTC(*curve, *ts)\n reconstructed = []\n\n # Knot errors\n error = 0\n for k, reconst in enumerate(reconstructed_iter):\n orig = elevated_quadratics[j + k]\n err = abs(reconst[3] - orig[3])\n error = max(error, err)\n if error > tolerance:\n break\n reconstructed.append(reconst)\n if error > tolerance:\n # Not feasible\n continue\n\n # Interior errors\n for k, reconst in enumerate(reconstructed):\n orig = elevated_quadratics[j + k]\n p0, p1, p2, p3 = tuple(v - u for v, u in zip(reconst, orig))\n\n if not cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):\n error = tolerance + 1\n break\n if error > tolerance:\n # Not feasible\n continue\n\n # Save best solution\n i_sol_count = j_sol_count + 3\n i_sol_error = max(j_sol_error, error)\n i_sol = Solution(i_sol_count, i_sol_error, i - j, True)\n if i_sol < best_sol:\n best_sol = i_sol\n\n if i_sol_count == 3:\n # Can't get any better than this\n break\n\n sols.append(best_sol)\n if i in forced:\n start = i\n\n # Reconstruct solution\n splits = []\n cubic = []\n i = len(sols) - 1\n while i:\n count, is_cubic = sols[i].start_index, sols[i].is_cubic\n splits.append(i)\n cubic.append(is_cubic)\n i -= count\n curves = []\n j = 0\n for i, is_cubic in reversed(list(zip(splits, cubic))):\n if is_cubic:\n curves.append(merge_curves(elevated_quadratics, j, i - j)[0])\n else:\n for k in range(j, i):\n curves.append(q[k * 2 : k * 2 + 3])\n j = i\n\n return curves\n\n\ndef main():\n from fontTools.cu2qu.benchmark import generate_curve\n from fontTools.cu2qu import curve_to_quadratic\n\n tolerance = 0.05\n reconstruct_tolerance = tolerance * 1\n curve = generate_curve()\n quadratics = curve_to_quadratic(curve, tolerance)\n print(\n "cu2qu tolerance %g. qu2cu tolerance %g." % (tolerance, reconstruct_tolerance)\n )\n print("One random cubic turned into %d quadratics." % len(quadratics))\n curves = quadratic_to_curves([quadratics], reconstruct_tolerance)\n print("Those quadratics turned back into %d cubics. " % len(curves))\n print("Original curve:", curve)\n print("Reconstructed curve(s):", curves)\n\n\nif __name__ == "__main__":\n main()\n
.venv\Lib\site-packages\fontTools\qu2cu\qu2cu.py
qu2cu.py
Python
12,693
0.95
0.138272
0.118343
react-lib
897
2023-08-04T21:53:02.141490
BSD-3-Clause
false
62c7b683a540eb30122932142c4b9a1d
# Copyright 2016 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the "License");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an "AS IS" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom .qu2cu import *\n
.venv\Lib\site-packages\fontTools\qu2cu\__init__.py
__init__.py
Python
633
0.95
0.066667
0.928571
node-utils
22
2024-05-13T20:02:59.187776
BSD-3-Clause
false
48af4e7dae0e258f595c5011d74d5718
import sys\n\nfrom .cli import _main as main\n\n\nif __name__ == "__main__":\n sys.exit(main())\n
.venv\Lib\site-packages\fontTools\qu2cu\__main__.py
__main__.py
Python
100
0.65
0.142857
0
python-kit
839
2024-09-05T00:53:52.122522
GPL-3.0
false
af11a743891a1118951ee8f584495ea5
\n\n
.venv\Lib\site-packages\fontTools\qu2cu\__pycache__\benchmark.cpython-313.pyc
benchmark.cpython-313.pyc
Other
2,922
0.95
0.03125
0
awesome-app
833
2025-03-13T16:52:45.833339
MIT
false
3c4d4deeeb50b789e3efb0d74c4bc6cd
\n\n
.venv\Lib\site-packages\fontTools\qu2cu\__pycache__\cli.cpython-313.pyc
cli.cpython-313.pyc
Other
5,267
0.8
0.032787
0
node-utils
856
2024-03-25T16:00:26.275471
GPL-3.0
false
7ba614a0d3916946654e71466e8bf743
\n\n
.venv\Lib\site-packages\fontTools\qu2cu\__pycache__\qu2cu.cpython-313.pyc
qu2cu.cpython-313.pyc
Other
14,329
0.95
0.021898
0.032129
vue-tools
859
2024-06-21T06:34:03.590401
BSD-3-Clause
false
099f65e94a531ac535e91a1c70126737
\n\n
.venv\Lib\site-packages\fontTools\qu2cu\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
219
0.7
0
0
node-utils
46
2025-06-18T03:23:14.771350
BSD-3-Clause
false
63fabfdf06a133d871e27f47755057ff
\n\n
.venv\Lib\site-packages\fontTools\qu2cu\__pycache__\__main__.cpython-313.pyc
__main__.cpython-313.pyc
Other
368
0.7
0
0
node-utils
754
2023-11-21T21:04:07.463493
GPL-3.0
false
4e70908bd38e374a1a3c81bd3875e41c
from fontTools.misc import psCharStrings\nfrom fontTools import ttLib\nfrom fontTools.pens.basePen import NullPen\nfrom fontTools.misc.roundTools import otRound\nfrom fontTools.misc.loggingTools import deprecateFunction\nfrom fontTools.subset.util import _add_method, _uniq_sort\n\n\nclass _ClosureGlyphsT2Decompiler(psCharStrings.SimpleT2Decompiler):\n def __init__(self, components, localSubrs, globalSubrs):\n psCharStrings.SimpleT2Decompiler.__init__(self, localSubrs, globalSubrs)\n self.components = components\n\n def op_endchar(self, index):\n args = self.popall()\n if len(args) >= 4:\n from fontTools.encodings.StandardEncoding import StandardEncoding\n\n # endchar can do seac accent bulding; The T2 spec says it's deprecated,\n # but recent software that shall remain nameless does output it.\n adx, ady, bchar, achar = args[-4:]\n baseGlyph = StandardEncoding[bchar]\n accentGlyph = StandardEncoding[achar]\n self.components.add(baseGlyph)\n self.components.add(accentGlyph)\n\n\n@_add_method(ttLib.getTableClass("CFF "))\ndef closure_glyphs(self, s):\n cff = self.cff\n assert len(cff) == 1\n font = cff[cff.keys()[0]]\n glyphSet = font.CharStrings\n\n decompose = s.glyphs\n while decompose:\n components = set()\n for g in decompose:\n if g not in glyphSet:\n continue\n gl = glyphSet[g]\n\n subrs = getattr(gl.private, "Subrs", [])\n decompiler = _ClosureGlyphsT2Decompiler(components, subrs, gl.globalSubrs)\n decompiler.execute(gl)\n components -= s.glyphs\n s.glyphs.update(components)\n decompose = components\n\n\ndef _empty_charstring(font, glyphName, isCFF2, ignoreWidth=False):\n c, fdSelectIndex = font.CharStrings.getItemAndSelector(glyphName)\n if isCFF2 or ignoreWidth:\n # CFF2 charstrings have no widths nor 'endchar' operators\n c.setProgram([] if isCFF2 else ["endchar"])\n else:\n if hasattr(font, "FDArray") and font.FDArray is not None:\n private = font.FDArray[fdSelectIndex].Private\n else:\n private = font.Private\n dfltWdX = private.defaultWidthX\n nmnlWdX = private.nominalWidthX\n pen = NullPen()\n c.draw(pen) # this will set the charstring's width\n if c.width != dfltWdX:\n c.program = [c.width - nmnlWdX, "endchar"]\n else:\n c.program = ["endchar"]\n\n\n@_add_method(ttLib.getTableClass("CFF "))\ndef prune_pre_subset(self, font, options):\n cff = self.cff\n # CFF table must have one font only\n cff.fontNames = cff.fontNames[:1]\n\n if options.notdef_glyph and not options.notdef_outline:\n isCFF2 = cff.major > 1\n for fontname in cff.keys():\n font = cff[fontname]\n _empty_charstring(font, ".notdef", isCFF2=isCFF2)\n\n # Clear useless Encoding\n for fontname in cff.keys():\n font = cff[fontname]\n # https://github.com/fonttools/fonttools/issues/620\n font.Encoding = "StandardEncoding"\n\n return True # bool(cff.fontNames)\n\n\n@_add_method(ttLib.getTableClass("CFF "))\ndef subset_glyphs(self, s):\n cff = self.cff\n for fontname in cff.keys():\n font = cff[fontname]\n cs = font.CharStrings\n\n glyphs = s.glyphs.union(s.glyphs_emptied)\n\n # Load all glyphs\n for g in font.charset:\n if g not in glyphs:\n continue\n c, _ = cs.getItemAndSelector(g)\n\n if cs.charStringsAreIndexed:\n indices = [i for i, g in enumerate(font.charset) if g in glyphs]\n csi = cs.charStringsIndex\n csi.items = [csi.items[i] for i in indices]\n del csi.file, csi.offsets\n if hasattr(font, "FDSelect"):\n sel = font.FDSelect\n sel.format = None\n sel.gidArray = [sel.gidArray[i] for i in indices]\n newCharStrings = {}\n for indicesIdx, charsetIdx in enumerate(indices):\n g = font.charset[charsetIdx]\n if g in cs.charStrings:\n newCharStrings[g] = indicesIdx\n cs.charStrings = newCharStrings\n else:\n cs.charStrings = {g: v for g, v in cs.charStrings.items() if g in glyphs}\n font.charset = [g for g in font.charset if g in glyphs]\n font.numGlyphs = len(font.charset)\n\n if s.options.retain_gids:\n isCFF2 = cff.major > 1\n for g in s.glyphs_emptied:\n _empty_charstring(font, g, isCFF2=isCFF2, ignoreWidth=True)\n\n return True # any(cff[fontname].numGlyphs for fontname in cff.keys())\n\n\n@_add_method(ttLib.getTableClass("CFF "))\ndef prune_post_subset(self, ttfFont, options):\n cff = self.cff\n for fontname in cff.keys():\n font = cff[fontname]\n cs = font.CharStrings\n\n # Drop unused FontDictionaries\n if hasattr(font, "FDSelect"):\n sel = font.FDSelect\n indices = _uniq_sort(sel.gidArray)\n sel.gidArray = [indices.index(ss) for ss in sel.gidArray]\n arr = font.FDArray\n arr.items = [arr[i] for i in indices]\n del arr.file, arr.offsets\n\n # Desubroutinize if asked for\n if options.desubroutinize:\n cff.desubroutinize()\n\n # Drop hints if not needed\n if not options.hinting:\n self.remove_hints()\n elif not options.desubroutinize:\n self.remove_unused_subroutines()\n return True\n\n\n@deprecateFunction(\n "use 'CFFFontSet.desubroutinize()' instead", category=DeprecationWarning\n)\n@_add_method(ttLib.getTableClass("CFF "))\ndef desubroutinize(self):\n self.cff.desubroutinize()\n\n\n@deprecateFunction(\n "use 'CFFFontSet.remove_hints()' instead", category=DeprecationWarning\n)\n@_add_method(ttLib.getTableClass("CFF "))\ndef remove_hints(self):\n self.cff.remove_hints()\n\n\n@deprecateFunction(\n "use 'CFFFontSet.remove_unused_subroutines' instead", category=DeprecationWarning\n)\n@_add_method(ttLib.getTableClass("CFF "))\ndef remove_unused_subroutines(self):\n self.cff.remove_unused_subroutines()\n
.venv\Lib\site-packages\fontTools\subset\cff.py
cff.py
Python
6,329
0.95
0.266304
0.066225
awesome-app
498
2024-05-16T19:42:46.354845
GPL-3.0
false
7fa208d9436f5fa049321c7595c73507
"""Private utility methods used by the subset modules"""\n\n\ndef _add_method(*clazzes):\n """Returns a decorator function that adds a new method to one or\n more classes."""\n\n def wrapper(method):\n done = []\n for clazz in clazzes:\n if clazz in done:\n continue # Support multiple names of a clazz\n done.append(clazz)\n assert clazz.__name__ != "DefaultTable", "Oops, table class not found."\n assert not hasattr(\n clazz, method.__name__\n ), "Oops, class '%s' has method '%s'." % (clazz.__name__, method.__name__)\n setattr(clazz, method.__name__, method)\n return None\n\n return wrapper\n\n\ndef _uniq_sort(l):\n return sorted(set(l))\n
.venv\Lib\site-packages\fontTools\subset\util.py
util.py
Python
779
0.95
0.32
0
vue-tools
184
2024-03-11T13:20:03.276595
GPL-3.0
false
eb671ccb1df0cb6689f5c888cdae055e
import sys\nfrom fontTools.subset import main\n\n\nif __name__ == "__main__":\n sys.exit(main())\n
.venv\Lib\site-packages\fontTools\subset\__main__.py
__main__.py
Python
101
0.65
0.166667
0
node-utils
126
2024-01-29T16:41:36.755879
MIT
false
8ec07662e78db18470c51db67908a6bc
\n\n
.venv\Lib\site-packages\fontTools\subset\__pycache__\cff.cpython-313.pyc
cff.cpython-313.pyc
Other
9,250
0.8
0
0.018868
python-kit
972
2024-07-01T18:55:28.299771
GPL-3.0
false
6ca1a88e5d73f9931399d8210dfeb154
\n\n
.venv\Lib\site-packages\fontTools\subset\__pycache__\svg.cpython-313.pyc
svg.cpython-313.pyc
Other
9,515
0.95
0
0
awesome-app
618
2023-07-28T19:04:59.472425
GPL-3.0
false
0abe14673350211906c4aaa807214df4
\n\n
.venv\Lib\site-packages\fontTools\subset\__pycache__\util.cpython-313.pyc
util.cpython-313.pyc
Other
1,305
0.95
0.25
0
vue-tools
662
2025-06-07T07:01:28.922943
GPL-3.0
false
265e5100872b18d386d18bda917a10ff
\n\n
.venv\Lib\site-packages\fontTools\subset\__pycache__\__main__.cpython-313.pyc
__main__.cpython-313.pyc
Other
370
0.7
0
0
vue-tools
525
2024-12-12T21:36:22.310414
BSD-3-Clause
false
48bda29b537aeb3f6b016069c2b9c4aa
from .path import SVGPath, parse_path\n\n__all__ = ["SVGPath", "parse_path"]\n
.venv\Lib\site-packages\fontTools\svgLib\__init__.py
__init__.py
Python
78
0.65
0
0
python-kit
909
2025-02-26T13:28:56.821865
GPL-3.0
false
a76d5989b122770b14cd9b282683f66f
"""Convert SVG Path's elliptical arcs to Bezier curves.\n\nThe code is mostly adapted from Blink's SVGPathNormalizer::DecomposeArcToCubic\nhttps://github.com/chromium/chromium/blob/93831f2/third_party/\nblink/renderer/core/svg/svg_path_parser.cc#L169-L278\n"""\n\nfrom fontTools.misc.transform import Identity, Scale\nfrom math import atan2, ceil, cos, fabs, isfinite, pi, radians, sin, sqrt, tan\n\n\nTWO_PI = 2 * pi\nPI_OVER_TWO = 0.5 * pi\n\n\ndef _map_point(matrix, pt):\n # apply Transform matrix to a point represented as a complex number\n r = matrix.transformPoint((pt.real, pt.imag))\n return r[0] + r[1] * 1j\n\n\nclass EllipticalArc(object):\n def __init__(self, current_point, rx, ry, rotation, large, sweep, target_point):\n self.current_point = current_point\n self.rx = rx\n self.ry = ry\n self.rotation = rotation\n self.large = large\n self.sweep = sweep\n self.target_point = target_point\n\n # SVG arc's rotation angle is expressed in degrees, whereas Transform.rotate\n # uses radians\n self.angle = radians(rotation)\n\n # these derived attributes are computed by the _parametrize method\n self.center_point = self.theta1 = self.theta2 = self.theta_arc = None\n\n def _parametrize(self):\n # convert from endopoint to center parametrization:\n # https://www.w3.org/TR/SVG/implnote.html#ArcConversionEndpointToCenter\n\n # If rx = 0 or ry = 0 then this arc is treated as a straight line segment (a\n # "lineto") joining the endpoints.\n # http://www.w3.org/TR/SVG/implnote.html#ArcOutOfRangeParameters\n rx = fabs(self.rx)\n ry = fabs(self.ry)\n if not (rx and ry):\n return False\n\n # If the current point and target point for the arc are identical, it should\n # be treated as a zero length path. This ensures continuity in animations.\n if self.target_point == self.current_point:\n return False\n\n mid_point_distance = (self.current_point - self.target_point) * 0.5\n\n point_transform = Identity.rotate(-self.angle)\n\n transformed_mid_point = _map_point(point_transform, mid_point_distance)\n square_rx = rx * rx\n square_ry = ry * ry\n square_x = transformed_mid_point.real * transformed_mid_point.real\n square_y = transformed_mid_point.imag * transformed_mid_point.imag\n\n # Check if the radii are big enough to draw the arc, scale radii if not.\n # http://www.w3.org/TR/SVG/implnote.html#ArcCorrectionOutOfRangeRadii\n radii_scale = square_x / square_rx + square_y / square_ry\n if radii_scale > 1:\n rx *= sqrt(radii_scale)\n ry *= sqrt(radii_scale)\n self.rx, self.ry = rx, ry\n\n point_transform = Scale(1 / rx, 1 / ry).rotate(-self.angle)\n\n point1 = _map_point(point_transform, self.current_point)\n point2 = _map_point(point_transform, self.target_point)\n delta = point2 - point1\n\n d = delta.real * delta.real + delta.imag * delta.imag\n scale_factor_squared = max(1 / d - 0.25, 0.0)\n\n scale_factor = sqrt(scale_factor_squared)\n if self.sweep == self.large:\n scale_factor = -scale_factor\n\n delta *= scale_factor\n center_point = (point1 + point2) * 0.5\n center_point += complex(-delta.imag, delta.real)\n point1 -= center_point\n point2 -= center_point\n\n theta1 = atan2(point1.imag, point1.real)\n theta2 = atan2(point2.imag, point2.real)\n\n theta_arc = theta2 - theta1\n if theta_arc < 0 and self.sweep:\n theta_arc += TWO_PI\n elif theta_arc > 0 and not self.sweep:\n theta_arc -= TWO_PI\n\n self.theta1 = theta1\n self.theta2 = theta1 + theta_arc\n self.theta_arc = theta_arc\n self.center_point = center_point\n\n return True\n\n def _decompose_to_cubic_curves(self):\n if self.center_point is None and not self._parametrize():\n return\n\n point_transform = Identity.rotate(self.angle).scale(self.rx, self.ry)\n\n # Some results of atan2 on some platform implementations are not exact\n # enough. So that we get more cubic curves than expected here. Adding 0.001f\n # reduces the count of sgements to the correct count.\n num_segments = int(ceil(fabs(self.theta_arc / (PI_OVER_TWO + 0.001))))\n for i in range(num_segments):\n start_theta = self.theta1 + i * self.theta_arc / num_segments\n end_theta = self.theta1 + (i + 1) * self.theta_arc / num_segments\n\n t = (4 / 3) * tan(0.25 * (end_theta - start_theta))\n if not isfinite(t):\n return\n\n sin_start_theta = sin(start_theta)\n cos_start_theta = cos(start_theta)\n sin_end_theta = sin(end_theta)\n cos_end_theta = cos(end_theta)\n\n point1 = complex(\n cos_start_theta - t * sin_start_theta,\n sin_start_theta + t * cos_start_theta,\n )\n point1 += self.center_point\n target_point = complex(cos_end_theta, sin_end_theta)\n target_point += self.center_point\n point2 = target_point\n point2 += complex(t * sin_end_theta, -t * cos_end_theta)\n\n point1 = _map_point(point_transform, point1)\n point2 = _map_point(point_transform, point2)\n target_point = _map_point(point_transform, target_point)\n\n yield point1, point2, target_point\n\n def draw(self, pen):\n for point1, point2, target_point in self._decompose_to_cubic_curves():\n pen.curveTo(\n (point1.real, point1.imag),\n (point2.real, point2.imag),\n (target_point.real, target_point.imag),\n )\n
.venv\Lib\site-packages\fontTools\svgLib\path\arc.py
arc.py
Python
5,966
0.95
0.116883
0.134454
vue-tools
789
2024-01-31T05:27:37.642204
BSD-3-Clause
false
db60b84acd303d6dc1aa908d669c850a
# SVG Path specification parser.\n# This is an adaptation from 'svg.path' by Lennart Regebro (@regebro),\n# modified so that the parser takes a FontTools Pen object instead of\n# returning a list of svg.path Path objects.\n# The original code can be found at:\n# https://github.com/regebro/svg.path/blob/4f9b6e3/src/svg/path/parser.py\n# Copyright (c) 2013-2014 Lennart Regebro\n# License: MIT\n\nfrom .arc import EllipticalArc\nimport re\n\n\nCOMMANDS = set("MmZzLlHhVvCcSsQqTtAa")\nARC_COMMANDS = set("Aa")\nUPPERCASE = set("MZLHVCSQTA")\n\nCOMMAND_RE = re.compile("([MmZzLlHhVvCcSsQqTtAa])")\n\n# https://www.w3.org/TR/css-syntax-3/#number-token-diagram\n# but -6.e-5 will be tokenized as "-6" then "-5" and confuse parsing\nFLOAT_RE = re.compile(\n r"[-+]?" # optional sign\n r"(?:"\n r"(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][-+]?[0-9]+)?" # int/float\n r"|"\n r"(?:\.[0-9]+(?:[eE][-+]?[0-9]+)?)" # float with leading dot (e.g. '.42')\n r")"\n)\nBOOL_RE = re.compile("^[01]")\nSEPARATOR_RE = re.compile(f"[, \t]")\n\n\ndef _tokenize_path(pathdef):\n arc_cmd = None\n for x in COMMAND_RE.split(pathdef):\n if x in COMMANDS:\n arc_cmd = x if x in ARC_COMMANDS else None\n yield x\n continue\n\n if arc_cmd:\n try:\n yield from _tokenize_arc_arguments(x)\n except ValueError as e:\n raise ValueError(f"Invalid arc command: '{arc_cmd}{x}'") from e\n else:\n for token in FLOAT_RE.findall(x):\n yield token\n\n\nARC_ARGUMENT_TYPES = (\n ("rx", FLOAT_RE),\n ("ry", FLOAT_RE),\n ("x-axis-rotation", FLOAT_RE),\n ("large-arc-flag", BOOL_RE),\n ("sweep-flag", BOOL_RE),\n ("x", FLOAT_RE),\n ("y", FLOAT_RE),\n)\n\n\ndef _tokenize_arc_arguments(arcdef):\n raw_args = [s for s in SEPARATOR_RE.split(arcdef) if s]\n if not raw_args:\n raise ValueError(f"Not enough arguments: '{arcdef}'")\n raw_args.reverse()\n\n i = 0\n while raw_args:\n arg = raw_args.pop()\n\n name, pattern = ARC_ARGUMENT_TYPES[i]\n match = pattern.search(arg)\n if not match:\n raise ValueError(f"Invalid argument for '{name}' parameter: {arg!r}")\n\n j, k = match.span()\n yield arg[j:k]\n arg = arg[k:]\n\n if arg:\n raw_args.append(arg)\n\n # wrap around every 7 consecutive arguments\n if i == 6:\n i = 0\n else:\n i += 1\n\n if i != 0:\n raise ValueError(f"Not enough arguments: '{arcdef}'")\n\n\ndef parse_path(pathdef, pen, current_pos=(0, 0), arc_class=EllipticalArc):\n """Parse SVG path definition (i.e. "d" attribute of <path> elements)\n and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath\n methods.\n\n If 'current_pos' (2-float tuple) is provided, the initial moveTo will\n be relative to that instead being absolute.\n\n If the pen has an "arcTo" method, it is called with the original values\n of the elliptical arc curve commands:\n\n .. code-block::\n\n pen.arcTo(rx, ry, rotation, arc_large, arc_sweep, (x, y))\n\n Otherwise, the arcs are approximated by series of cubic Bezier segments\n ("curveTo"), one every 90 degrees.\n """\n # In the SVG specs, initial movetos are absolute, even if\n # specified as 'm'. This is the default behavior here as well.\n # But if you pass in a current_pos variable, the initial moveto\n # will be relative to that current_pos. This is useful.\n current_pos = complex(*current_pos)\n\n elements = list(_tokenize_path(pathdef))\n # Reverse for easy use of .pop()\n elements.reverse()\n\n start_pos = None\n command = None\n last_control = None\n\n have_arcTo = hasattr(pen, "arcTo")\n\n while elements:\n if elements[-1] in COMMANDS:\n # New command.\n last_command = command # Used by S and T\n command = elements.pop()\n absolute = command in UPPERCASE\n command = command.upper()\n else:\n # If this element starts with numbers, it is an implicit command\n # and we don't change the command. Check that it's allowed:\n if command is None:\n raise ValueError(\n "Unallowed implicit command in %s, position %s"\n % (pathdef, len(pathdef.split()) - len(elements))\n )\n last_command = command # Used by S and T\n\n if command == "M":\n # Moveto command.\n x = elements.pop()\n y = elements.pop()\n pos = float(x) + float(y) * 1j\n if absolute:\n current_pos = pos\n else:\n current_pos += pos\n\n # M is not preceded by Z; it's an open subpath\n if start_pos is not None:\n pen.endPath()\n\n pen.moveTo((current_pos.real, current_pos.imag))\n\n # when M is called, reset start_pos\n # This behavior of Z is defined in svg spec:\n # http://www.w3.org/TR/SVG/paths.html#PathDataClosePathCommand\n start_pos = current_pos\n\n # Implicit moveto commands are treated as lineto commands.\n # So we set command to lineto here, in case there are\n # further implicit commands after this moveto.\n command = "L"\n\n elif command == "Z":\n # Close path\n if current_pos != start_pos:\n pen.lineTo((start_pos.real, start_pos.imag))\n pen.closePath()\n current_pos = start_pos\n start_pos = None\n command = None # You can't have implicit commands after closing.\n\n elif command == "L":\n x = elements.pop()\n y = elements.pop()\n pos = float(x) + float(y) * 1j\n if not absolute:\n pos += current_pos\n pen.lineTo((pos.real, pos.imag))\n current_pos = pos\n\n elif command == "H":\n x = elements.pop()\n pos = float(x) + current_pos.imag * 1j\n if not absolute:\n pos += current_pos.real\n pen.lineTo((pos.real, pos.imag))\n current_pos = pos\n\n elif command == "V":\n y = elements.pop()\n pos = current_pos.real + float(y) * 1j\n if not absolute:\n pos += current_pos.imag * 1j\n pen.lineTo((pos.real, pos.imag))\n current_pos = pos\n\n elif command == "C":\n control1 = float(elements.pop()) + float(elements.pop()) * 1j\n control2 = float(elements.pop()) + float(elements.pop()) * 1j\n end = float(elements.pop()) + float(elements.pop()) * 1j\n\n if not absolute:\n control1 += current_pos\n control2 += current_pos\n end += current_pos\n\n pen.curveTo(\n (control1.real, control1.imag),\n (control2.real, control2.imag),\n (end.real, end.imag),\n )\n current_pos = end\n last_control = control2\n\n elif command == "S":\n # Smooth curve. First control point is the "reflection" of\n # the second control point in the previous path.\n\n if last_command not in "CS":\n # If there is no previous command or if the previous command\n # was not an C, c, S or s, assume the first control point is\n # coincident with the current point.\n control1 = current_pos\n else:\n # The first control point is assumed to be the reflection of\n # the second control point on the previous command relative\n # to the current point.\n control1 = current_pos + current_pos - last_control\n\n control2 = float(elements.pop()) + float(elements.pop()) * 1j\n end = float(elements.pop()) + float(elements.pop()) * 1j\n\n if not absolute:\n control2 += current_pos\n end += current_pos\n\n pen.curveTo(\n (control1.real, control1.imag),\n (control2.real, control2.imag),\n (end.real, end.imag),\n )\n current_pos = end\n last_control = control2\n\n elif command == "Q":\n control = float(elements.pop()) + float(elements.pop()) * 1j\n end = float(elements.pop()) + float(elements.pop()) * 1j\n\n if not absolute:\n control += current_pos\n end += current_pos\n\n pen.qCurveTo((control.real, control.imag), (end.real, end.imag))\n current_pos = end\n last_control = control\n\n elif command == "T":\n # Smooth curve. Control point is the "reflection" of\n # the second control point in the previous path.\n\n if last_command not in "QT":\n # If there is no previous command or if the previous command\n # was not an Q, q, T or t, assume the first control point is\n # coincident with the current point.\n control = current_pos\n else:\n # The control point is assumed to be the reflection of\n # the control point on the previous command relative\n # to the current point.\n control = current_pos + current_pos - last_control\n\n end = float(elements.pop()) + float(elements.pop()) * 1j\n\n if not absolute:\n end += current_pos\n\n pen.qCurveTo((control.real, control.imag), (end.real, end.imag))\n current_pos = end\n last_control = control\n\n elif command == "A":\n rx = abs(float(elements.pop()))\n ry = abs(float(elements.pop()))\n rotation = float(elements.pop())\n arc_large = bool(int(elements.pop()))\n arc_sweep = bool(int(elements.pop()))\n end = float(elements.pop()) + float(elements.pop()) * 1j\n\n if not absolute:\n end += current_pos\n\n # if the pen supports arcs, pass the values unchanged, otherwise\n # approximate the arc with a series of cubic bezier curves\n if have_arcTo:\n pen.arcTo(\n rx,\n ry,\n rotation,\n arc_large,\n arc_sweep,\n (end.real, end.imag),\n )\n else:\n arc = arc_class(\n current_pos, rx, ry, rotation, arc_large, arc_sweep, end\n )\n arc.draw(pen)\n\n current_pos = end\n\n # no final Z command, it's an open path\n if start_pos is not None:\n pen.endPath()\n
.venv\Lib\site-packages\fontTools\svgLib\path\parser.py
parser.py
Python
11,110
0.95
0.13354
0.178707
awesome-app
617
2025-02-13T04:30:07.967317
GPL-3.0
false
95894db7cf36edd939f7fbbec88c04a9
from fontTools.pens.transformPen import TransformPen\nfrom fontTools.misc import etree\nfrom fontTools.misc.textTools import tostr\nfrom .parser import parse_path\nfrom .shapes import PathBuilder\n\n\n__all__ = [tostr(s) for s in ("SVGPath", "parse_path")]\n\n\nclass SVGPath(object):\n """Parse SVG ``path`` elements from a file or string, and draw them\n onto a glyph object that supports the FontTools Pen protocol.\n\n For example, reading from an SVG file and drawing to a Defcon Glyph:\n\n .. code-block::\n\n import defcon\n glyph = defcon.Glyph()\n pen = glyph.getPen()\n svg = SVGPath("path/to/a.svg")\n svg.draw(pen)\n\n Or reading from a string containing SVG data, using the alternative\n 'fromstring' (a class method):\n\n .. code-block::\n\n data = '<?xml version="1.0" ...'\n svg = SVGPath.fromstring(data)\n svg.draw(pen)\n\n Both constructors can optionally take a 'transform' matrix (6-float\n tuple, or a FontTools Transform object) to modify the draw output.\n """\n\n def __init__(self, filename=None, transform=None):\n if filename is None:\n self.root = etree.ElementTree()\n else:\n tree = etree.parse(filename)\n self.root = tree.getroot()\n self.transform = transform\n\n @classmethod\n def fromstring(cls, data, transform=None):\n self = cls(transform=transform)\n self.root = etree.fromstring(data)\n return self\n\n def draw(self, pen):\n if self.transform:\n pen = TransformPen(pen, self.transform)\n pb = PathBuilder()\n # xpath | doesn't seem to reliable work so just walk it\n for el in self.root.iter():\n pb.add_path_from_element(el)\n original_pen = pen\n for path, transform in zip(pb.paths, pb.transforms):\n if transform:\n pen = TransformPen(original_pen, transform)\n else:\n pen = original_pen\n parse_path(path, pen)\n
.venv\Lib\site-packages\fontTools\svgLib\path\__init__.py
__init__.py
Python
2,061
0.95
0.169231
0.019608
python-kit
939
2023-12-23T15:55:39.735165
Apache-2.0
false
0dac4625bb1542f581e28ab740185bf7
\n\n
.venv\Lib\site-packages\fontTools\svgLib\path\__pycache__\arc.cpython-313.pyc
arc.cpython-313.pyc
Other
6,667
0.8
0
0
vue-tools
704
2025-06-06T17:51:40.462147
MIT
false
f1d3632a993abf1aef44dedeec8882cc
\n\n
.venv\Lib\site-packages\fontTools\svgLib\path\__pycache__\parser.cpython-313.pyc
parser.cpython-313.pyc
Other
9,696
0.8
0.00578
0.006211
awesome-app
641
2024-08-04T14:22:44.966548
Apache-2.0
false
a4f651d2c9203edf09627397aec3e034
\n\n
.venv\Lib\site-packages\fontTools\svgLib\path\__pycache__\shapes.cpython-313.pyc
shapes.cpython-313.pyc
Other
10,863
0.8
0
0
awesome-app
533
2025-06-20T11:39:31.047974
Apache-2.0
false
2c54158b9e47744d4761aebd7b92af48
\n\n
.venv\Lib\site-packages\fontTools\svgLib\path\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
2,935
0.95
0.021739
0
react-lib
445
2025-06-28T06:55:41.574185
MIT
false
cc5ee27efa56f4569ce5f20bea352434
\n\n
.venv\Lib\site-packages\fontTools\svgLib\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
288
0.8
0
0.25
python-kit
969
2024-03-12T23:55:04.922996
MIT
false
e0cf22b949e7462e784895796675f52d
\n\n
.venv\Lib\site-packages\fontTools\t1Lib\__pycache__\__init__.cpython-313.pyc
__init__.cpython-313.pyc
Other
27,030
0.95
0.028754
0.003425
awesome-app
192
2023-09-17T06:59:40.686314
GPL-3.0
false
26ad7f4b21876432bab8468f3fd7d7cc
"""ttLib.macUtils.py -- Various Mac-specific stuff."""\n\nfrom io import BytesIO\nfrom fontTools.misc.macRes import ResourceReader, ResourceError\n\n\ndef getSFNTResIndices(path):\n """Determine whether a file has a 'sfnt' resource fork or not."""\n try:\n reader = ResourceReader(path)\n indices = reader.getIndices("sfnt")\n reader.close()\n return indices\n except ResourceError:\n return []\n\n\ndef openTTFonts(path):\n """Given a pathname, return a list of TTFont objects. In the case\n of a flat TTF/OTF file, the list will contain just one font object;\n but in the case of a Mac font suitcase it will contain as many\n font objects as there are sfnt resources in the file.\n """\n from fontTools import ttLib\n\n fonts = []\n sfnts = getSFNTResIndices(path)\n if not sfnts:\n fonts.append(ttLib.TTFont(path))\n else:\n for index in sfnts:\n fonts.append(ttLib.TTFont(path, index))\n if not fonts:\n raise ttLib.TTLibError("no fonts found in file '%s'" % path)\n return fonts\n\n\nclass SFNTResourceReader(BytesIO):\n """Simple read-only file wrapper for 'sfnt' resources."""\n\n def __init__(self, path, res_name_or_index):\n from fontTools import ttLib\n\n reader = ResourceReader(path)\n if isinstance(res_name_or_index, str):\n rsrc = reader.getNamedResource("sfnt", res_name_or_index)\n else:\n rsrc = reader.getIndResource("sfnt", res_name_or_index)\n if rsrc is None:\n raise ttLib.TTLibError("sfnt resource not found: %s" % res_name_or_index)\n reader.close()\n self.rsrc = rsrc\n super(SFNTResourceReader, self).__init__(rsrc.data)\n self.name = path\n
.venv\Lib\site-packages\fontTools\ttLib\macUtils.py
macUtils.py
Python
1,791
0.85
0.203704
0
node-utils
771
2025-05-27T17:08:47.018114
BSD-3-Clause
false
0d36179b51c257797bc9ef1921ebeab4
""" Simplify TrueType glyphs by merging overlapping contours/components.\n\nRequires https://github.com/fonttools/skia-pathops\n"""\n\nimport itertools\nimport logging\nfrom typing import Callable, Iterable, Optional, Mapping\n\nfrom fontTools.cffLib import CFFFontSet\nfrom fontTools.ttLib import ttFont\nfrom fontTools.ttLib.tables import _g_l_y_f\nfrom fontTools.ttLib.tables import _h_m_t_x\nfrom fontTools.misc.psCharStrings import T2CharString\nfrom fontTools.misc.roundTools import otRound, noRound\nfrom fontTools.pens.ttGlyphPen import TTGlyphPen\nfrom fontTools.pens.t2CharStringPen import T2CharStringPen\n\nimport pathops\n\n\n__all__ = ["removeOverlaps"]\n\n\nclass RemoveOverlapsError(Exception):\n pass\n\n\nlog = logging.getLogger("fontTools.ttLib.removeOverlaps")\n\n_TTGlyphMapping = Mapping[str, ttFont._TTGlyph]\n\n\ndef skPathFromGlyph(glyphName: str, glyphSet: _TTGlyphMapping) -> pathops.Path:\n path = pathops.Path()\n pathPen = path.getPen(glyphSet=glyphSet)\n glyphSet[glyphName].draw(pathPen)\n return path\n\n\ndef skPathFromGlyphComponent(\n component: _g_l_y_f.GlyphComponent, glyphSet: _TTGlyphMapping\n):\n baseGlyphName, transformation = component.getComponentInfo()\n path = skPathFromGlyph(baseGlyphName, glyphSet)\n return path.transform(*transformation)\n\n\ndef componentsOverlap(glyph: _g_l_y_f.Glyph, glyphSet: _TTGlyphMapping) -> bool:\n if not glyph.isComposite():\n raise ValueError("This method only works with TrueType composite glyphs")\n if len(glyph.components) < 2:\n return False # single component, no overlaps\n\n component_paths = {}\n\n def _get_nth_component_path(index: int) -> pathops.Path:\n if index not in component_paths:\n component_paths[index] = skPathFromGlyphComponent(\n glyph.components[index], glyphSet\n )\n return component_paths[index]\n\n return any(\n pathops.op(\n _get_nth_component_path(i),\n _get_nth_component_path(j),\n pathops.PathOp.INTERSECTION,\n fix_winding=False,\n keep_starting_points=False,\n )\n for i, j in itertools.combinations(range(len(glyph.components)), 2)\n )\n\n\ndef ttfGlyphFromSkPath(path: pathops.Path) -> _g_l_y_f.Glyph:\n # Skia paths have no 'components', no need for glyphSet\n ttPen = TTGlyphPen(glyphSet=None)\n path.draw(ttPen)\n glyph = ttPen.glyph()\n assert not glyph.isComposite()\n # compute glyph.xMin (glyfTable parameter unused for non composites)\n glyph.recalcBounds(glyfTable=None)\n return glyph\n\n\ndef _charString_from_SkPath(\n path: pathops.Path, charString: T2CharString\n) -> T2CharString:\n if charString.width == charString.private.defaultWidthX:\n width = None\n else:\n width = charString.width - charString.private.nominalWidthX\n t2Pen = T2CharStringPen(width=width, glyphSet=None)\n path.draw(t2Pen)\n return t2Pen.getCharString(charString.private, charString.globalSubrs)\n\n\ndef _round_path(\n path: pathops.Path, round: Callable[[float], float] = otRound\n) -> pathops.Path:\n rounded_path = pathops.Path()\n for verb, points in path:\n rounded_path.add(verb, *((round(p[0]), round(p[1])) for p in points))\n return rounded_path\n\n\ndef _simplify(\n path: pathops.Path,\n debugGlyphName: str,\n *,\n round: Callable[[float], float] = otRound,\n) -> pathops.Path:\n # skia-pathops has a bug where it sometimes fails to simplify paths when there\n # are float coordinates and control points are very close to one another.\n # Rounding coordinates to integers works around the bug.\n # Since we are going to round glyf coordinates later on anyway, here it is\n # ok(-ish) to also round before simplify. Better than failing the whole process\n # for the entire font.\n # https://bugs.chromium.org/p/skia/issues/detail?id=11958\n # https://github.com/google/fonts/issues/3365\n # TODO(anthrotype): remove once this Skia bug is fixed\n try:\n return pathops.simplify(path, clockwise=path.clockwise)\n except pathops.PathOpsError:\n pass\n\n path = _round_path(path, round=round)\n try:\n path = pathops.simplify(path, clockwise=path.clockwise)\n log.debug(\n "skia-pathops failed to simplify '%s' with float coordinates, "\n "but succeded using rounded integer coordinates",\n debugGlyphName,\n )\n return path\n except pathops.PathOpsError as e:\n if log.isEnabledFor(logging.DEBUG):\n path.dump()\n raise RemoveOverlapsError(\n f"Failed to remove overlaps from glyph {debugGlyphName!r}"\n ) from e\n\n raise AssertionError("Unreachable")\n\n\ndef _same_path(path1: pathops.Path, path2: pathops.Path) -> bool:\n return {tuple(c) for c in path1.contours} == {tuple(c) for c in path2.contours}\n\n\ndef removeTTGlyphOverlaps(\n glyphName: str,\n glyphSet: _TTGlyphMapping,\n glyfTable: _g_l_y_f.table__g_l_y_f,\n hmtxTable: _h_m_t_x.table__h_m_t_x,\n removeHinting: bool = True,\n) -> bool:\n glyph = glyfTable[glyphName]\n # decompose composite glyphs only if components overlap each other\n if (\n glyph.numberOfContours > 0\n or glyph.isComposite()\n and componentsOverlap(glyph, glyphSet)\n ):\n path = skPathFromGlyph(glyphName, glyphSet)\n\n # remove overlaps\n path2 = _simplify(path, glyphName)\n\n # replace TTGlyph if simplified path is different (ignoring contour order)\n if not _same_path(path, path2):\n glyfTable[glyphName] = glyph = ttfGlyphFromSkPath(path2)\n # simplified glyph is always unhinted\n assert not glyph.program\n # also ensure hmtx LSB == glyph.xMin so glyph origin is at x=0\n width, lsb = hmtxTable[glyphName]\n if lsb != glyph.xMin:\n hmtxTable[glyphName] = (width, glyph.xMin)\n return True\n\n if removeHinting:\n glyph.removeHinting()\n return False\n\n\ndef _remove_glyf_overlaps(\n *,\n font: ttFont.TTFont,\n glyphNames: Iterable[str],\n glyphSet: _TTGlyphMapping,\n removeHinting: bool,\n ignoreErrors: bool,\n) -> None:\n glyfTable = font["glyf"]\n hmtxTable = font["hmtx"]\n\n # process all simple glyphs first, then composites with increasing component depth,\n # so that by the time we test for component intersections the respective base glyphs\n # have already been simplified\n glyphNames = sorted(\n glyphNames,\n key=lambda name: (\n (\n glyfTable[name].getCompositeMaxpValues(glyfTable).maxComponentDepth\n if glyfTable[name].isComposite()\n else 0\n ),\n name,\n ),\n )\n modified = set()\n for glyphName in glyphNames:\n try:\n if removeTTGlyphOverlaps(\n glyphName, glyphSet, glyfTable, hmtxTable, removeHinting\n ):\n modified.add(glyphName)\n except RemoveOverlapsError:\n if not ignoreErrors:\n raise\n log.error("Failed to remove overlaps for '%s'", glyphName)\n\n log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))\n\n\ndef _remove_charstring_overlaps(\n *,\n glyphName: str,\n glyphSet: _TTGlyphMapping,\n cffFontSet: CFFFontSet,\n) -> bool:\n path = skPathFromGlyph(glyphName, glyphSet)\n\n # remove overlaps\n path2 = _simplify(path, glyphName, round=noRound)\n\n # replace TTGlyph if simplified path is different (ignoring contour order)\n if not _same_path(path, path2):\n charStrings = cffFontSet[0].CharStrings\n charStrings[glyphName] = _charString_from_SkPath(path2, charStrings[glyphName])\n return True\n\n return False\n\n\ndef _remove_cff_overlaps(\n *,\n font: ttFont.TTFont,\n glyphNames: Iterable[str],\n glyphSet: _TTGlyphMapping,\n removeHinting: bool,\n ignoreErrors: bool,\n removeUnusedSubroutines: bool = True,\n) -> None:\n cffFontSet = font["CFF "].cff\n modified = set()\n for glyphName in glyphNames:\n try:\n if _remove_charstring_overlaps(\n glyphName=glyphName,\n glyphSet=glyphSet,\n cffFontSet=cffFontSet,\n ):\n modified.add(glyphName)\n except RemoveOverlapsError:\n if not ignoreErrors:\n raise\n log.error("Failed to remove overlaps for '%s'", glyphName)\n\n if not modified:\n log.debug("No overlaps found in the specified CFF glyphs")\n return\n\n if removeHinting:\n cffFontSet.remove_hints()\n\n if removeUnusedSubroutines:\n cffFontSet.remove_unused_subroutines()\n\n log.debug("Removed overlaps for %s glyphs:\n%s", len(modified), " ".join(modified))\n\n\ndef removeOverlaps(\n font: ttFont.TTFont,\n glyphNames: Optional[Iterable[str]] = None,\n removeHinting: bool = True,\n ignoreErrors: bool = False,\n *,\n removeUnusedSubroutines: bool = True,\n) -> None:\n """Simplify glyphs in TTFont by merging overlapping contours.\n\n Overlapping components are first decomposed to simple contours, then merged.\n\n Currently this only works for fonts with 'glyf' or 'CFF ' tables.\n Raises NotImplementedError if 'glyf' or 'CFF ' tables are absent.\n\n Note that removing overlaps invalidates the hinting. By default we drop hinting\n from all glyphs whether or not overlaps are removed from a given one, as it would\n look weird if only some glyphs are left (un)hinted.\n\n Args:\n font: input TTFont object, modified in place.\n glyphNames: optional iterable of glyph names (str) to remove overlaps from.\n By default, all glyphs in the font are processed.\n removeHinting (bool): set to False to keep hinting for unmodified glyphs.\n ignoreErrors (bool): set to True to ignore errors while removing overlaps,\n thus keeping the tricky glyphs unchanged (fonttools/fonttools#2363).\n removeUnusedSubroutines (bool): set to False to keep unused subroutines\n in CFF table after removing overlaps. Default is to remove them if\n any glyphs are modified.\n """\n\n if "glyf" not in font and "CFF " not in font:\n raise NotImplementedError(\n "No outline data found in the font: missing 'glyf' or 'CFF ' table"\n )\n\n if glyphNames is None:\n glyphNames = font.getGlyphOrder()\n\n # Wraps the underlying glyphs, takes care of interfacing with drawing pens\n glyphSet = font.getGlyphSet()\n\n if "glyf" in font:\n _remove_glyf_overlaps(\n font=font,\n glyphNames=glyphNames,\n glyphSet=glyphSet,\n removeHinting=removeHinting,\n ignoreErrors=ignoreErrors,\n )\n\n if "CFF " in font:\n _remove_cff_overlaps(\n font=font,\n glyphNames=glyphNames,\n glyphSet=glyphSet,\n removeHinting=removeHinting,\n ignoreErrors=ignoreErrors,\n removeUnusedSubroutines=removeUnusedSubroutines,\n )\n\n\ndef main(args=None):\n """Simplify glyphs in TTFont by merging overlapping contours."""\n\n import argparse\n\n parser = argparse.ArgumentParser(\n "fonttools ttLib.removeOverlaps", description=__doc__\n )\n\n parser.add_argument("input", metavar="INPUT.ttf", help="Input font file")\n parser.add_argument("output", metavar="OUTPUT.ttf", help="Output font file")\n parser.add_argument(\n "glyphs",\n metavar="GLYPHS",\n nargs="*",\n help="Optional list of glyph names to remove overlaps from",\n )\n parser.add_argument(\n "--keep-hinting",\n action="store_true",\n help="Keep hinting for unmodified glyphs, default is to drop hinting",\n )\n parser.add_argument(\n "--ignore-errors",\n action="store_true",\n help="ignore errors while removing overlaps, "\n "thus keeping the tricky glyphs unchanged",\n )\n parser.add_argument(\n "--keep-unused-subroutines",\n action="store_true",\n help="Keep unused subroutines in CFF table after removing overlaps, "\n "default is to remove them if any glyphs are modified",\n )\n args = parser.parse_args(args)\n\n with ttFont.TTFont(args.input) as font:\n removeOverlaps(\n font=font,\n glyphNames=args.glyphs or None,\n removeHinting=not args.keep_hinting,\n ignoreErrors=args.ignore_errors,\n removeUnusedSubroutines=not args.keep_unused_subroutines,\n )\n font.save(args.output)\n\n\nif __name__ == "__main__":\n main()\n
.venv\Lib\site-packages\fontTools\ttLib\removeOverlaps.py
removeOverlaps.py
Python
13,005
0.95
0.178117
0.083851
react-lib
218
2024-06-24T14:03:42.557256
Apache-2.0
false
2e5eecc6d96073420332e904dd449547
"""Change the units-per-EM of a font.\n\nAAT and Graphite tables are not supported. CFF/CFF2 fonts\nare de-subroutinized."""\n\nfrom fontTools.ttLib.ttVisitor import TTVisitor\nimport fontTools.ttLib as ttLib\nimport fontTools.ttLib.tables.otBase as otBase\nimport fontTools.ttLib.tables.otTables as otTables\nfrom fontTools.cffLib import VarStoreData\nimport fontTools.cffLib.specializer as cffSpecializer\nfrom fontTools.varLib import builder # for VarData.calculateNumShorts\nfrom fontTools.varLib.multiVarStore import OnlineMultiVarStoreBuilder\nfrom fontTools.misc.vector import Vector\nfrom fontTools.misc.fixedTools import otRound\nfrom fontTools.misc.iterTools import batched\n\n\n__all__ = ["scale_upem", "ScalerVisitor"]\n\n\nclass ScalerVisitor(TTVisitor):\n def __init__(self, scaleFactor):\n self.scaleFactor = scaleFactor\n\n def scale(self, v):\n return otRound(v * self.scaleFactor)\n\n\n@ScalerVisitor.register_attrs(\n (\n (ttLib.getTableClass("head"), ("unitsPerEm", "xMin", "yMin", "xMax", "yMax")),\n (ttLib.getTableClass("post"), ("underlinePosition", "underlineThickness")),\n (ttLib.getTableClass("VORG"), ("defaultVertOriginY")),\n (\n ttLib.getTableClass("hhea"),\n (\n "ascent",\n "descent",\n "lineGap",\n "advanceWidthMax",\n "minLeftSideBearing",\n "minRightSideBearing",\n "xMaxExtent",\n "caretOffset",\n ),\n ),\n (\n ttLib.getTableClass("vhea"),\n (\n "ascent",\n "descent",\n "lineGap",\n "advanceHeightMax",\n "minTopSideBearing",\n "minBottomSideBearing",\n "yMaxExtent",\n "caretOffset",\n ),\n ),\n (\n ttLib.getTableClass("OS/2"),\n (\n "xAvgCharWidth",\n "ySubscriptXSize",\n "ySubscriptYSize",\n "ySubscriptXOffset",\n "ySubscriptYOffset",\n "ySuperscriptXSize",\n "ySuperscriptYSize",\n "ySuperscriptXOffset",\n "ySuperscriptYOffset",\n "yStrikeoutSize",\n "yStrikeoutPosition",\n "sTypoAscender",\n "sTypoDescender",\n "sTypoLineGap",\n "usWinAscent",\n "usWinDescent",\n "sxHeight",\n "sCapHeight",\n ),\n ),\n (\n otTables.ValueRecord,\n ("XAdvance", "YAdvance", "XPlacement", "YPlacement"),\n ), # GPOS\n (otTables.Anchor, ("XCoordinate", "YCoordinate")), # GPOS\n (otTables.CaretValue, ("Coordinate")), # GDEF\n (otTables.BaseCoord, ("Coordinate")), # BASE\n (otTables.MathValueRecord, ("Value")), # MATH\n (otTables.ClipBox, ("xMin", "yMin", "xMax", "yMax")), # COLR\n )\n)\ndef visit(visitor, obj, attr, value):\n setattr(obj, attr, visitor.scale(value))\n\n\n@ScalerVisitor.register_attr(\n (ttLib.getTableClass("hmtx"), ttLib.getTableClass("vmtx")), "metrics"\n)\ndef visit(visitor, obj, attr, metrics):\n for g in metrics:\n advance, lsb = metrics[g]\n metrics[g] = visitor.scale(advance), visitor.scale(lsb)\n\n\n@ScalerVisitor.register_attr(ttLib.getTableClass("VMTX"), "VOriginRecords")\ndef visit(visitor, obj, attr, VOriginRecords):\n for g in VOriginRecords:\n VOriginRecords[g] = visitor.scale(VOriginRecords[g])\n\n\n@ScalerVisitor.register_attr(ttLib.getTableClass("glyf"), "glyphs")\ndef visit(visitor, obj, attr, glyphs):\n for g in glyphs.values():\n for attr in ("xMin", "xMax", "yMin", "yMax"):\n v = getattr(g, attr, None)\n if v is not None:\n setattr(g, attr, visitor.scale(v))\n\n if g.isComposite():\n for component in g.components:\n component.x = visitor.scale(component.x)\n component.y = visitor.scale(component.y)\n continue\n\n if hasattr(g, "coordinates"):\n coordinates = g.coordinates\n for i, (x, y) in enumerate(coordinates):\n coordinates[i] = visitor.scale(x), visitor.scale(y)\n\n\n@ScalerVisitor.register_attr(ttLib.getTableClass("gvar"), "variations")\ndef visit(visitor, obj, attr, variations):\n glyfTable = visitor.font["glyf"]\n\n for glyphName, varlist in variations.items():\n glyph = glyfTable[glyphName]\n for var in varlist:\n coordinates = var.coordinates\n for i, xy in enumerate(coordinates):\n if xy is None:\n continue\n coordinates[i] = visitor.scale(xy[0]), visitor.scale(xy[1])\n\n\n@ScalerVisitor.register_attr(ttLib.getTableClass("VARC"), "table")\ndef visit(visitor, obj, attr, varc):\n # VarComposite variations are a pain\n\n fvar = visitor.font["fvar"]\n fvarAxes = [a.axisTag for a in fvar.axes]\n\n store = varc.MultiVarStore\n storeBuilder = OnlineMultiVarStoreBuilder(fvarAxes)\n\n for g in varc.VarCompositeGlyphs.VarCompositeGlyph:\n for component in g.components:\n t = component.transform\n t.translateX = visitor.scale(t.translateX)\n t.translateY = visitor.scale(t.translateY)\n t.tCenterX = visitor.scale(t.tCenterX)\n t.tCenterY = visitor.scale(t.tCenterY)\n\n if component.axisValuesVarIndex != otTables.NO_VARIATION_INDEX:\n varIdx = component.axisValuesVarIndex\n # TODO Move this code duplicated below to MultiVarStore.__getitem__,\n # or a getDeltasAndSupports().\n if varIdx != otTables.NO_VARIATION_INDEX:\n major = varIdx >> 16\n minor = varIdx & 0xFFFF\n varData = store.MultiVarData[major]\n vec = varData.Item[minor]\n storeBuilder.setSupports(store.get_supports(major, fvar.axes))\n if vec:\n m = len(vec) // varData.VarRegionCount\n vec = list(batched(vec, m))\n vec = [Vector(v) for v in vec]\n component.axisValuesVarIndex = storeBuilder.storeDeltas(vec)\n else:\n component.axisValuesVarIndex = otTables.NO_VARIATION_INDEX\n\n if component.transformVarIndex != otTables.NO_VARIATION_INDEX:\n varIdx = component.transformVarIndex\n if varIdx != otTables.NO_VARIATION_INDEX:\n major = varIdx >> 16\n minor = varIdx & 0xFFFF\n vec = varData.Item[varIdx & 0xFFFF]\n major = varIdx >> 16\n minor = varIdx & 0xFFFF\n varData = store.MultiVarData[major]\n vec = varData.Item[minor]\n storeBuilder.setSupports(store.get_supports(major, fvar.axes))\n if vec:\n m = len(vec) // varData.VarRegionCount\n flags = component.flags\n vec = list(batched(vec, m))\n newVec = []\n for v in vec:\n v = list(v)\n i = 0\n ## Scale translate & tCenter\n if flags & otTables.VarComponentFlags.HAVE_TRANSLATE_X:\n v[i] = visitor.scale(v[i])\n i += 1\n if flags & otTables.VarComponentFlags.HAVE_TRANSLATE_Y:\n v[i] = visitor.scale(v[i])\n i += 1\n if flags & otTables.VarComponentFlags.HAVE_ROTATION:\n i += 1\n if flags & otTables.VarComponentFlags.HAVE_SCALE_X:\n i += 1\n if flags & otTables.VarComponentFlags.HAVE_SCALE_Y:\n i += 1\n if flags & otTables.VarComponentFlags.HAVE_SKEW_X:\n i += 1\n if flags & otTables.VarComponentFlags.HAVE_SKEW_Y:\n i += 1\n if flags & otTables.VarComponentFlags.HAVE_TCENTER_X:\n v[i] = visitor.scale(v[i])\n i += 1\n if flags & otTables.VarComponentFlags.HAVE_TCENTER_Y:\n v[i] = visitor.scale(v[i])\n i += 1\n\n newVec.append(Vector(v))\n vec = newVec\n\n component.transformVarIndex = storeBuilder.storeDeltas(vec)\n else:\n component.transformVarIndex = otTables.NO_VARIATION_INDEX\n\n varc.MultiVarStore = storeBuilder.finish()\n\n\n@ScalerVisitor.register_attr(ttLib.getTableClass("kern"), "kernTables")\ndef visit(visitor, obj, attr, kernTables):\n for table in kernTables:\n kernTable = table.kernTable\n for k in kernTable.keys():\n kernTable[k] = visitor.scale(kernTable[k])\n\n\ndef _cff_scale(visitor, args):\n for i, arg in enumerate(args):\n if not isinstance(arg, list):\n if not isinstance(arg, bytes):\n args[i] = visitor.scale(arg)\n else:\n num_blends = arg[-1]\n _cff_scale(visitor, arg)\n arg[-1] = num_blends\n\n\n@ScalerVisitor.register_attr(\n (ttLib.getTableClass("CFF "), ttLib.getTableClass("CFF2")), "cff"\n)\ndef visit(visitor, obj, attr, cff):\n cff.desubroutinize()\n topDict = cff.topDictIndex[0]\n varStore = getattr(topDict, "VarStore", None)\n getNumRegions = varStore.getNumRegions if varStore is not None else None\n privates = set()\n for fontname in cff.keys():\n font = cff[fontname]\n cs = font.CharStrings\n for g in font.charset:\n c, _ = cs.getItemAndSelector(g)\n privates.add(c.private)\n\n commands = cffSpecializer.programToCommands(\n c.program, getNumRegions=getNumRegions\n )\n for op, args in commands:\n if op == "vsindex":\n continue\n _cff_scale(visitor, args)\n c.program[:] = cffSpecializer.commandsToProgram(commands)\n\n # Annoying business of scaling numbers that do not matter whatsoever\n\n for attr in (\n "UnderlinePosition",\n "UnderlineThickness",\n "FontBBox",\n "StrokeWidth",\n ):\n value = getattr(topDict, attr, None)\n if value is None:\n continue\n if isinstance(value, list):\n _cff_scale(visitor, value)\n else:\n setattr(topDict, attr, visitor.scale(value))\n\n for i in range(6):\n topDict.FontMatrix[i] /= visitor.scaleFactor\n\n for private in privates:\n for attr in (\n "BlueValues",\n "OtherBlues",\n "FamilyBlues",\n "FamilyOtherBlues",\n # "BlueScale",\n # "BlueShift",\n # "BlueFuzz",\n "StdHW",\n "StdVW",\n "StemSnapH",\n "StemSnapV",\n "defaultWidthX",\n "nominalWidthX",\n ):\n value = getattr(private, attr, None)\n if value is None:\n continue\n if isinstance(value, list):\n _cff_scale(visitor, value)\n else:\n setattr(private, attr, visitor.scale(value))\n\n\n# ItemVariationStore\n\n\n@ScalerVisitor.register(otTables.VarData)\ndef visit(visitor, varData):\n for item in varData.Item:\n for i, v in enumerate(item):\n item[i] = visitor.scale(v)\n varData.calculateNumShorts()\n\n\n# COLRv1\n\n\ndef _setup_scale_paint(paint, scale):\n if -2 <= scale <= 2 - (1 >> 14):\n paint.Format = otTables.PaintFormat.PaintScaleUniform\n paint.scale = scale\n return\n\n transform = otTables.Affine2x3()\n transform.populateDefaults()\n transform.xy = transform.yx = transform.dx = transform.dy = 0\n transform.xx = transform.yy = scale\n\n paint.Format = otTables.PaintFormat.PaintTransform\n paint.Transform = transform\n\n\n@ScalerVisitor.register(otTables.BaseGlyphPaintRecord)\ndef visit(visitor, record):\n oldPaint = record.Paint\n\n scale = otTables.Paint()\n _setup_scale_paint(scale, visitor.scaleFactor)\n scale.Paint = oldPaint\n\n record.Paint = scale\n\n return True\n\n\n@ScalerVisitor.register(otTables.Paint)\ndef visit(visitor, paint):\n if paint.Format != otTables.PaintFormat.PaintGlyph:\n return True\n\n newPaint = otTables.Paint()\n newPaint.Format = paint.Format\n newPaint.Paint = paint.Paint\n newPaint.Glyph = paint.Glyph\n del paint.Paint\n del paint.Glyph\n\n _setup_scale_paint(paint, 1 / visitor.scaleFactor)\n paint.Paint = newPaint\n\n visitor.visit(newPaint.Paint)\n\n return False\n\n\ndef scale_upem(font, new_upem):\n """Change the units-per-EM of font to the new value."""\n upem = font["head"].unitsPerEm\n visitor = ScalerVisitor(new_upem / upem)\n visitor.visit(font)\n\n\ndef main(args=None):\n """Change the units-per-EM of fonts"""\n\n if args is None:\n import sys\n\n args = sys.argv[1:]\n\n from fontTools.ttLib import TTFont\n from fontTools.misc.cliTools import makeOutputFileName\n import argparse\n\n parser = argparse.ArgumentParser(\n "fonttools ttLib.scaleUpem", description="Change the units-per-EM of fonts"\n )\n parser.add_argument("font", metavar="font", help="Font file.")\n parser.add_argument(\n "new_upem", metavar="new-upem", help="New units-per-EM integer value."\n )\n parser.add_argument(\n "--output-file", metavar="path", default=None, help="Output file."\n )\n\n options = parser.parse_args(args)\n\n font = TTFont(options.font)\n new_upem = int(options.new_upem)\n output_file = (\n options.output_file\n if options.output_file is not None\n else makeOutputFileName(options.font, overWrite=True, suffix="-scaled")\n )\n\n scale_upem(font, new_upem)\n\n print("Writing %s" % output_file)\n font.save(output_file)\n\n\nif __name__ == "__main__":\n import sys\n\n sys.exit(main())\n
.venv\Lib\site-packages\fontTools\ttLib\scaleUpem.py
scaleUpem.py
Python
15,054
0.95
0.176606
0.027855
vue-tools
542
2025-05-17T23:35:47.337596
GPL-3.0
false
13e7134d6df6bd53ab9bfe61b67f7d97
"""ttLib/sfnt.py -- low-level module to deal with the sfnt file format.\n\nDefines two public classes:\n\n- SFNTReader\n- SFNTWriter\n\n(Normally you don't have to use these classes explicitly; they are\nused automatically by ttLib.TTFont.)\n\nThe reading and writing of sfnt files is separated in two distinct\nclasses, since whenever the number of tables changes or whenever\na table's length changes you need to rewrite the whole file anyway.\n"""\n\nfrom io import BytesIO\nfrom types import SimpleNamespace\nfrom fontTools.misc.textTools import Tag\nfrom fontTools.misc import sstruct\nfrom fontTools.ttLib import TTLibError, TTLibFileIsCollectionError\nimport struct\nfrom collections import OrderedDict\nimport logging\n\n\nlog = logging.getLogger(__name__)\n\n\nclass SFNTReader(object):\n def __new__(cls, *args, **kwargs):\n """Return an instance of the SFNTReader sub-class which is compatible\n with the input file type.\n """\n if args and cls is SFNTReader:\n infile = args[0]\n infile.seek(0)\n sfntVersion = Tag(infile.read(4))\n infile.seek(0)\n if sfntVersion == "wOF2":\n # return new WOFF2Reader object\n from fontTools.ttLib.woff2 import WOFF2Reader\n\n return object.__new__(WOFF2Reader)\n # return default object\n return object.__new__(cls)\n\n def __init__(self, file, checkChecksums=0, fontNumber=-1):\n self.file = file\n self.checkChecksums = checkChecksums\n\n self.flavor = None\n self.flavorData = None\n self.DirectoryEntry = SFNTDirectoryEntry\n self.file.seek(0)\n self.sfntVersion = self.file.read(4)\n self.file.seek(0)\n if self.sfntVersion == b"ttcf":\n header = readTTCHeader(self.file)\n numFonts = header.numFonts\n if not 0 <= fontNumber < numFonts:\n raise TTLibFileIsCollectionError(\n "specify a font number between 0 and %d (inclusive)"\n % (numFonts - 1)\n )\n self.numFonts = numFonts\n self.file.seek(header.offsetTable[fontNumber])\n data = self.file.read(sfntDirectorySize)\n if len(data) != sfntDirectorySize:\n raise TTLibError("Not a Font Collection (not enough data)")\n sstruct.unpack(sfntDirectoryFormat, data, self)\n elif self.sfntVersion == b"wOFF":\n self.flavor = "woff"\n self.DirectoryEntry = WOFFDirectoryEntry\n data = self.file.read(woffDirectorySize)\n if len(data) != woffDirectorySize:\n raise TTLibError("Not a WOFF font (not enough data)")\n sstruct.unpack(woffDirectoryFormat, data, self)\n else:\n data = self.file.read(sfntDirectorySize)\n if len(data) != sfntDirectorySize:\n raise TTLibError("Not a TrueType or OpenType font (not enough data)")\n sstruct.unpack(sfntDirectoryFormat, data, self)\n self.sfntVersion = Tag(self.sfntVersion)\n\n if self.sfntVersion not in ("\x00\x01\x00\x00", "OTTO", "true"):\n raise TTLibError("Not a TrueType or OpenType font (bad sfntVersion)")\n tables = {}\n for i in range(self.numTables):\n entry = self.DirectoryEntry()\n entry.fromFile(self.file)\n tag = Tag(entry.tag)\n tables[tag] = entry\n self.tables = OrderedDict(sorted(tables.items(), key=lambda i: i[1].offset))\n\n # Load flavor data if any\n if self.flavor == "woff":\n self.flavorData = WOFFFlavorData(self)\n\n def has_key(self, tag):\n return tag in self.tables\n\n __contains__ = has_key\n\n def keys(self):\n return self.tables.keys()\n\n def __getitem__(self, tag):\n """Fetch the raw table data."""\n entry = self.tables[Tag(tag)]\n data = entry.loadData(self.file)\n if self.checkChecksums:\n if tag == "head":\n # Beh: we have to special-case the 'head' table.\n checksum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])\n else:\n checksum = calcChecksum(data)\n if self.checkChecksums > 1:\n # Be obnoxious, and barf when it's wrong\n assert checksum == entry.checkSum, "bad checksum for '%s' table" % tag\n elif checksum != entry.checkSum:\n # Be friendly, and just log a warning.\n log.warning("bad checksum for '%s' table", tag)\n return data\n\n def __delitem__(self, tag):\n del self.tables[Tag(tag)]\n\n def close(self):\n self.file.close()\n\n # We define custom __getstate__ and __setstate__ to make SFNTReader pickle-able\n # and deepcopy-able. When a TTFont is loaded as lazy=True, SFNTReader holds a\n # reference to an external file object which is not pickleable. So in __getstate__\n # we store the file name and current position, and in __setstate__ we reopen the\n # same named file after unpickling.\n\n def __getstate__(self):\n if isinstance(self.file, BytesIO):\n # BytesIO is already pickleable, return the state unmodified\n return self.__dict__\n\n # remove unpickleable file attribute, and only store its name and pos\n state = self.__dict__.copy()\n del state["file"]\n state["_filename"] = self.file.name\n state["_filepos"] = self.file.tell()\n return state\n\n def __setstate__(self, state):\n if "file" not in state:\n self.file = open(state.pop("_filename"), "rb")\n self.file.seek(state.pop("_filepos"))\n self.__dict__.update(state)\n\n\n# default compression level for WOFF 1.0 tables and metadata\nZLIB_COMPRESSION_LEVEL = 6\n\n# if set to True, use zopfli instead of zlib for compressing WOFF 1.0.\n# The Python bindings are available at https://pypi.python.org/pypi/zopfli\nUSE_ZOPFLI = False\n\n# mapping between zlib's compression levels and zopfli's 'numiterations'.\n# Use lower values for files over several MB in size or it will be too slow\nZOPFLI_LEVELS = {\n # 0: 0, # can't do 0 iterations...\n 1: 1,\n 2: 3,\n 3: 5,\n 4: 8,\n 5: 10,\n 6: 15,\n 7: 25,\n 8: 50,\n 9: 100,\n}\n\n\ndef compress(data, level=ZLIB_COMPRESSION_LEVEL):\n """Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True,\n zopfli is used instead of the zlib module.\n The compression 'level' must be between 0 and 9. 1 gives best speed,\n 9 gives best compression (0 gives no compression at all).\n The default value is a compromise between speed and compression (6).\n """\n if not (0 <= level <= 9):\n raise ValueError("Bad compression level: %s" % level)\n if not USE_ZOPFLI or level == 0:\n from zlib import compress\n\n return compress(data, level)\n else:\n from zopfli.zlib import compress\n\n return compress(data, numiterations=ZOPFLI_LEVELS[level])\n\n\nclass SFNTWriter(object):\n def __new__(cls, *args, **kwargs):\n """Return an instance of the SFNTWriter sub-class which is compatible\n with the specified 'flavor'.\n """\n flavor = None\n if kwargs and "flavor" in kwargs:\n flavor = kwargs["flavor"]\n elif args and len(args) > 3:\n flavor = args[3]\n if cls is SFNTWriter:\n if flavor == "woff2":\n # return new WOFF2Writer object\n from fontTools.ttLib.woff2 import WOFF2Writer\n\n return object.__new__(WOFF2Writer)\n # return default object\n return object.__new__(cls)\n\n def __init__(\n self,\n file,\n numTables,\n sfntVersion="\000\001\000\000",\n flavor=None,\n flavorData=None,\n ):\n self.file = file\n self.numTables = numTables\n self.sfntVersion = Tag(sfntVersion)\n self.flavor = flavor\n self.flavorData = flavorData\n\n if self.flavor == "woff":\n self.directoryFormat = woffDirectoryFormat\n self.directorySize = woffDirectorySize\n self.DirectoryEntry = WOFFDirectoryEntry\n\n self.signature = "wOFF"\n\n # to calculate WOFF checksum adjustment, we also need the original SFNT offsets\n self.origNextTableOffset = (\n sfntDirectorySize + numTables * sfntDirectoryEntrySize\n )\n else:\n assert not self.flavor, "Unknown flavor '%s'" % self.flavor\n self.directoryFormat = sfntDirectoryFormat\n self.directorySize = sfntDirectorySize\n self.DirectoryEntry = SFNTDirectoryEntry\n\n from fontTools.ttLib import getSearchRange\n\n self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(\n numTables, 16\n )\n\n self.directoryOffset = self.file.tell()\n self.nextTableOffset = (\n self.directoryOffset\n + self.directorySize\n + numTables * self.DirectoryEntry.formatSize\n )\n # clear out directory area\n self.file.seek(self.nextTableOffset)\n # make sure we're actually where we want to be. (old cStringIO bug)\n self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))\n self.tables = OrderedDict()\n\n def setEntry(self, tag, entry):\n if tag in self.tables:\n raise TTLibError("cannot rewrite '%s' table" % tag)\n\n self.tables[tag] = entry\n\n def __setitem__(self, tag, data):\n """Write raw table data to disk."""\n if tag in self.tables:\n raise TTLibError("cannot rewrite '%s' table" % tag)\n\n entry = self.DirectoryEntry()\n entry.tag = tag\n entry.offset = self.nextTableOffset\n if tag == "head":\n entry.checkSum = calcChecksum(data[:8] + b"\0\0\0\0" + data[12:])\n self.headTable = data\n entry.uncompressed = True\n else:\n entry.checkSum = calcChecksum(data)\n entry.saveData(self.file, data)\n\n if self.flavor == "woff":\n entry.origOffset = self.origNextTableOffset\n self.origNextTableOffset += (entry.origLength + 3) & ~3\n\n self.nextTableOffset = self.nextTableOffset + ((entry.length + 3) & ~3)\n # Add NUL bytes to pad the table data to a 4-byte boundary.\n # Don't depend on f.seek() as we need to add the padding even if no\n # subsequent write follows (seek is lazy), ie. after the final table\n # in the font.\n self.file.write(b"\0" * (self.nextTableOffset - self.file.tell()))\n assert self.nextTableOffset == self.file.tell()\n\n self.setEntry(tag, entry)\n\n def __getitem__(self, tag):\n return self.tables[tag]\n\n def close(self):\n """All tables must have been written to disk. Now write the\n directory.\n """\n tables = sorted(self.tables.items())\n if len(tables) != self.numTables:\n raise TTLibError(\n "wrong number of tables; expected %d, found %d"\n % (self.numTables, len(tables))\n )\n\n if self.flavor == "woff":\n self.signature = b"wOFF"\n self.reserved = 0\n\n self.totalSfntSize = 12\n self.totalSfntSize += 16 * len(tables)\n for tag, entry in tables:\n self.totalSfntSize += (entry.origLength + 3) & ~3\n\n data = self.flavorData if self.flavorData else WOFFFlavorData()\n if data.majorVersion is not None and data.minorVersion is not None:\n self.majorVersion = data.majorVersion\n self.minorVersion = data.minorVersion\n else:\n if hasattr(self, "headTable"):\n self.majorVersion, self.minorVersion = struct.unpack(\n ">HH", self.headTable[4:8]\n )\n else:\n self.majorVersion = self.minorVersion = 0\n if data.metaData:\n self.metaOrigLength = len(data.metaData)\n self.file.seek(0, 2)\n self.metaOffset = self.file.tell()\n compressedMetaData = compress(data.metaData)\n self.metaLength = len(compressedMetaData)\n self.file.write(compressedMetaData)\n else:\n self.metaOffset = self.metaLength = self.metaOrigLength = 0\n if data.privData:\n self.file.seek(0, 2)\n off = self.file.tell()\n paddedOff = (off + 3) & ~3\n self.file.write(b"\0" * (paddedOff - off))\n self.privOffset = self.file.tell()\n self.privLength = len(data.privData)\n self.file.write(data.privData)\n else:\n self.privOffset = self.privLength = 0\n\n self.file.seek(0, 2)\n self.length = self.file.tell()\n\n else:\n assert not self.flavor, "Unknown flavor '%s'" % self.flavor\n pass\n\n directory = sstruct.pack(self.directoryFormat, self)\n\n self.file.seek(self.directoryOffset + self.directorySize)\n seenHead = 0\n for tag, entry in tables:\n if tag == "head":\n seenHead = 1\n directory = directory + entry.toString()\n if seenHead:\n self.writeMasterChecksum(directory)\n self.file.seek(self.directoryOffset)\n self.file.write(directory)\n\n def _calcMasterChecksum(self, directory):\n # calculate checkSumAdjustment\n tags = list(self.tables.keys())\n checksums = []\n for i in range(len(tags)):\n checksums.append(self.tables[tags[i]].checkSum)\n\n if self.DirectoryEntry != SFNTDirectoryEntry:\n # Create a SFNT directory for checksum calculation purposes\n from fontTools.ttLib import getSearchRange\n\n self.searchRange, self.entrySelector, self.rangeShift = getSearchRange(\n self.numTables, 16\n )\n directory = sstruct.pack(sfntDirectoryFormat, self)\n tables = sorted(self.tables.items())\n for tag, entry in tables:\n sfntEntry = SFNTDirectoryEntry()\n sfntEntry.tag = entry.tag\n sfntEntry.checkSum = entry.checkSum\n sfntEntry.offset = entry.origOffset\n sfntEntry.length = entry.origLength\n directory = directory + sfntEntry.toString()\n\n directory_end = sfntDirectorySize + len(self.tables) * sfntDirectoryEntrySize\n assert directory_end == len(directory)\n\n checksums.append(calcChecksum(directory))\n checksum = sum(checksums) & 0xFFFFFFFF\n # BiboAfba!\n checksumadjustment = (0xB1B0AFBA - checksum) & 0xFFFFFFFF\n return checksumadjustment\n\n def writeMasterChecksum(self, directory):\n checksumadjustment = self._calcMasterChecksum(directory)\n # write the checksum to the file\n self.file.seek(self.tables["head"].offset + 8)\n self.file.write(struct.pack(">L", checksumadjustment))\n\n def reordersTables(self):\n return False\n\n\n# -- sfnt directory helpers and cruft\n\nttcHeaderFormat = """\n > # big endian\n TTCTag: 4s # "ttcf"\n Version: L # 0x00010000 or 0x00020000\n numFonts: L # number of fonts\n # OffsetTable[numFonts]: L # array with offsets from beginning of file\n # ulDsigTag: L # version 2.0 only\n # ulDsigLength: L # version 2.0 only\n # ulDsigOffset: L # version 2.0 only\n"""\n\nttcHeaderSize = sstruct.calcsize(ttcHeaderFormat)\n\nsfntDirectoryFormat = """\n > # big endian\n sfntVersion: 4s\n numTables: H # number of tables\n searchRange: H # (max2 <= numTables)*16\n entrySelector: H # log2(max2 <= numTables)\n rangeShift: H # numTables*16-searchRange\n"""\n\nsfntDirectorySize = sstruct.calcsize(sfntDirectoryFormat)\n\nsfntDirectoryEntryFormat = """\n > # big endian\n tag: 4s\n checkSum: L\n offset: L\n length: L\n"""\n\nsfntDirectoryEntrySize = sstruct.calcsize(sfntDirectoryEntryFormat)\n\nwoffDirectoryFormat = """\n > # big endian\n signature: 4s # "wOFF"\n sfntVersion: 4s\n length: L # total woff file size\n numTables: H # number of tables\n reserved: H # set to 0\n totalSfntSize: L # uncompressed size\n majorVersion: H # major version of WOFF file\n minorVersion: H # minor version of WOFF file\n metaOffset: L # offset to metadata block\n metaLength: L # length of compressed metadata\n metaOrigLength: L # length of uncompressed metadata\n privOffset: L # offset to private data block\n privLength: L # length of private data block\n"""\n\nwoffDirectorySize = sstruct.calcsize(woffDirectoryFormat)\n\nwoffDirectoryEntryFormat = """\n > # big endian\n tag: 4s\n offset: L\n length: L # compressed length\n origLength: L # original length\n checkSum: L # original checksum\n"""\n\nwoffDirectoryEntrySize = sstruct.calcsize(woffDirectoryEntryFormat)\n\n\nclass DirectoryEntry(object):\n def __init__(self):\n self.uncompressed = False # if True, always embed entry raw\n\n def fromFile(self, file):\n sstruct.unpack(self.format, file.read(self.formatSize), self)\n\n def fromString(self, str):\n sstruct.unpack(self.format, str, self)\n\n def toString(self):\n return sstruct.pack(self.format, self)\n\n def __repr__(self):\n if hasattr(self, "tag"):\n return "<%s '%s' at %x>" % (self.__class__.__name__, self.tag, id(self))\n else:\n return "<%s at %x>" % (self.__class__.__name__, id(self))\n\n def loadData(self, file):\n file.seek(self.offset)\n data = file.read(self.length)\n assert len(data) == self.length\n if hasattr(self.__class__, "decodeData"):\n data = self.decodeData(data)\n return data\n\n def saveData(self, file, data):\n if hasattr(self.__class__, "encodeData"):\n data = self.encodeData(data)\n self.length = len(data)\n file.seek(self.offset)\n file.write(data)\n\n def decodeData(self, rawData):\n return rawData\n\n def encodeData(self, data):\n return data\n\n\nclass SFNTDirectoryEntry(DirectoryEntry):\n format = sfntDirectoryEntryFormat\n formatSize = sfntDirectoryEntrySize\n\n\nclass WOFFDirectoryEntry(DirectoryEntry):\n format = woffDirectoryEntryFormat\n formatSize = woffDirectoryEntrySize\n\n def __init__(self):\n super(WOFFDirectoryEntry, self).__init__()\n # With fonttools<=3.1.2, the only way to set a different zlib\n # compression level for WOFF directory entries was to set the class\n # attribute 'zlibCompressionLevel'. This is now replaced by a globally\n # defined `ZLIB_COMPRESSION_LEVEL`, which is also applied when\n # compressing the metadata. For backward compatibility, we still\n # use the class attribute if it was already set.\n if not hasattr(WOFFDirectoryEntry, "zlibCompressionLevel"):\n self.zlibCompressionLevel = ZLIB_COMPRESSION_LEVEL\n\n def decodeData(self, rawData):\n import zlib\n\n if self.length == self.origLength:\n data = rawData\n else:\n assert self.length < self.origLength\n data = zlib.decompress(rawData)\n assert len(data) == self.origLength\n return data\n\n def encodeData(self, data):\n self.origLength = len(data)\n if not self.uncompressed:\n compressedData = compress(data, self.zlibCompressionLevel)\n if self.uncompressed or len(compressedData) >= self.origLength:\n # Encode uncompressed\n rawData = data\n self.length = self.origLength\n else:\n rawData = compressedData\n self.length = len(rawData)\n return rawData\n\n\nclass WOFFFlavorData:\n Flavor = "woff"\n\n def __init__(self, reader=None):\n self.majorVersion = None\n self.minorVersion = None\n self.metaData = None\n self.privData = None\n if reader:\n self.majorVersion = reader.majorVersion\n self.minorVersion = reader.minorVersion\n if reader.metaLength:\n reader.file.seek(reader.metaOffset)\n rawData = reader.file.read(reader.metaLength)\n assert len(rawData) == reader.metaLength\n data = self._decompress(rawData)\n assert len(data) == reader.metaOrigLength\n self.metaData = data\n if reader.privLength:\n reader.file.seek(reader.privOffset)\n data = reader.file.read(reader.privLength)\n assert len(data) == reader.privLength\n self.privData = data\n\n def _decompress(self, rawData):\n import zlib\n\n return zlib.decompress(rawData)\n\n\ndef calcChecksum(data):\n """Calculate the checksum for an arbitrary block of data.\n\n If the data length is not a multiple of four, it assumes\n it is to be padded with null byte.\n\n >>> print(calcChecksum(b"abcd"))\n 1633837924\n >>> print(calcChecksum(b"abcdxyz"))\n 3655064932\n """\n remainder = len(data) % 4\n if remainder:\n data += b"\0" * (4 - remainder)\n value = 0\n blockSize = 4096\n assert blockSize % 4 == 0\n for i in range(0, len(data), blockSize):\n block = data[i : i + blockSize]\n longs = struct.unpack(">%dL" % (len(block) // 4), block)\n value = (value + sum(longs)) & 0xFFFFFFFF\n return value\n\n\ndef readTTCHeader(file):\n file.seek(0)\n data = file.read(ttcHeaderSize)\n if len(data) != ttcHeaderSize:\n raise TTLibError("Not a Font Collection (not enough data)")\n self = SimpleNamespace()\n sstruct.unpack(ttcHeaderFormat, data, self)\n if self.TTCTag != "ttcf":\n raise TTLibError("Not a Font Collection")\n assert self.Version == 0x00010000 or self.Version == 0x00020000, (\n "unrecognized TTC version 0x%08x" % self.Version\n )\n self.offsetTable = struct.unpack(\n ">%dL" % self.numFonts, file.read(self.numFonts * 4)\n )\n if self.Version == 0x00020000:\n pass # ignoring version 2.0 signatures\n return self\n\n\ndef writeTTCHeader(file, numFonts):\n self = SimpleNamespace()\n self.TTCTag = "ttcf"\n self.Version = 0x00010000\n self.numFonts = numFonts\n file.seek(0)\n file.write(sstruct.pack(ttcHeaderFormat, self))\n offset = file.tell()\n file.write(struct.pack(">%dL" % self.numFonts, *([0] * self.numFonts)))\n return offset\n\n\nif __name__ == "__main__":\n import sys\n import doctest\n\n sys.exit(doctest.testmod().failed)\n
.venv\Lib\site-packages\fontTools\ttLib\sfnt.py
sfnt.py
Python
23,494
0.95
0.172205
0.079855
react-lib
400
2023-11-30T18:10:37.546623
GPL-3.0
false
aa572d303086f7a97c7e55667d15181c
#\n# 'post' table formats 1.0 and 2.0 rely on this list of "standard"\n# glyphs.\n#\n# My list is correct according to the Apple documentation for the 'post' table:\n# https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6post.html\n# (However, it seems that TTFdump (from MS) and FontLab disagree, at\n# least with respect to the last glyph, which they list as 'dslash'\n# instead of 'dcroat'.)\n#\n\nstandardGlyphOrder = [\n ".notdef", # 0\n ".null", # 1\n "nonmarkingreturn", # 2\n "space", # 3\n "exclam", # 4\n "quotedbl", # 5\n "numbersign", # 6\n "dollar", # 7\n "percent", # 8\n "ampersand", # 9\n "quotesingle", # 10\n "parenleft", # 11\n "parenright", # 12\n "asterisk", # 13\n "plus", # 14\n "comma", # 15\n "hyphen", # 16\n "period", # 17\n "slash", # 18\n "zero", # 19\n "one", # 20\n "two", # 21\n "three", # 22\n "four", # 23\n "five", # 24\n "six", # 25\n "seven", # 26\n "eight", # 27\n "nine", # 28\n "colon", # 29\n "semicolon", # 30\n "less", # 31\n "equal", # 32\n "greater", # 33\n "question", # 34\n "at", # 35\n "A", # 36\n "B", # 37\n "C", # 38\n "D", # 39\n "E", # 40\n "F", # 41\n "G", # 42\n "H", # 43\n "I", # 44\n "J", # 45\n "K", # 46\n "L", # 47\n "M", # 48\n "N", # 49\n "O", # 50\n "P", # 51\n "Q", # 52\n "R", # 53\n "S", # 54\n "T", # 55\n "U", # 56\n "V", # 57\n "W", # 58\n "X", # 59\n "Y", # 60\n "Z", # 61\n "bracketleft", # 62\n "backslash", # 63\n "bracketright", # 64\n "asciicircum", # 65\n "underscore", # 66\n "grave", # 67\n "a", # 68\n "b", # 69\n "c", # 70\n "d", # 71\n "e", # 72\n "f", # 73\n "g", # 74\n "h", # 75\n "i", # 76\n "j", # 77\n "k", # 78\n "l", # 79\n "m", # 80\n "n", # 81\n "o", # 82\n "p", # 83\n "q", # 84\n "r", # 85\n "s", # 86\n "t", # 87\n "u", # 88\n "v", # 89\n "w", # 90\n "x", # 91\n "y", # 92\n "z", # 93\n "braceleft", # 94\n "bar", # 95\n "braceright", # 96\n "asciitilde", # 97\n "Adieresis", # 98\n "Aring", # 99\n "Ccedilla", # 100\n "Eacute", # 101\n "Ntilde", # 102\n "Odieresis", # 103\n "Udieresis", # 104\n "aacute", # 105\n "agrave", # 106\n "acircumflex", # 107\n "adieresis", # 108\n "atilde", # 109\n "aring", # 110\n "ccedilla", # 111\n "eacute", # 112\n "egrave", # 113\n "ecircumflex", # 114\n "edieresis", # 115\n "iacute", # 116\n "igrave", # 117\n "icircumflex", # 118\n "idieresis", # 119\n "ntilde", # 120\n "oacute", # 121\n "ograve", # 122\n "ocircumflex", # 123\n "odieresis", # 124\n "otilde", # 125\n "uacute", # 126\n "ugrave", # 127\n "ucircumflex", # 128\n "udieresis", # 129\n "dagger", # 130\n "degree", # 131\n "cent", # 132\n "sterling", # 133\n "section", # 134\n "bullet", # 135\n "paragraph", # 136\n "germandbls", # 137\n "registered", # 138\n "copyright", # 139\n "trademark", # 140\n "acute", # 141\n "dieresis", # 142\n "notequal", # 143\n "AE", # 144\n "Oslash", # 145\n "infinity", # 146\n "plusminus", # 147\n "lessequal", # 148\n "greaterequal", # 149\n "yen", # 150\n "mu", # 151\n "partialdiff", # 152\n "summation", # 153\n "product", # 154\n "pi", # 155\n "integral", # 156\n "ordfeminine", # 157\n "ordmasculine", # 158\n "Omega", # 159\n "ae", # 160\n "oslash", # 161\n "questiondown", # 162\n "exclamdown", # 163\n "logicalnot", # 164\n "radical", # 165\n "florin", # 166\n "approxequal", # 167\n "Delta", # 168\n "guillemotleft", # 169\n "guillemotright", # 170\n "ellipsis", # 171\n "nonbreakingspace", # 172\n "Agrave", # 173\n "Atilde", # 174\n "Otilde", # 175\n "OE", # 176\n "oe", # 177\n "endash", # 178\n "emdash", # 179\n "quotedblleft", # 180\n "quotedblright", # 181\n "quoteleft", # 182\n "quoteright", # 183\n "divide", # 184\n "lozenge", # 185\n "ydieresis", # 186\n "Ydieresis", # 187\n "fraction", # 188\n "currency", # 189\n "guilsinglleft", # 190\n "guilsinglright", # 191\n "fi", # 192\n "fl", # 193\n "daggerdbl", # 194\n "periodcentered", # 195\n "quotesinglbase", # 196\n "quotedblbase", # 197\n "perthousand", # 198\n "Acircumflex", # 199\n "Ecircumflex", # 200\n "Aacute", # 201\n "Edieresis", # 202\n "Egrave", # 203\n "Iacute", # 204\n "Icircumflex", # 205\n "Idieresis", # 206\n "Igrave", # 207\n "Oacute", # 208\n "Ocircumflex", # 209\n "apple", # 210\n "Ograve", # 211\n "Uacute", # 212\n "Ucircumflex", # 213\n "Ugrave", # 214\n "dotlessi", # 215\n "circumflex", # 216\n "tilde", # 217\n "macron", # 218\n "breve", # 219\n "dotaccent", # 220\n "ring", # 221\n "cedilla", # 222\n "hungarumlaut", # 223\n "ogonek", # 224\n "caron", # 225\n "Lslash", # 226\n "lslash", # 227\n "Scaron", # 228\n "scaron", # 229\n "Zcaron", # 230\n "zcaron", # 231\n "brokenbar", # 232\n "Eth", # 233\n "eth", # 234\n "Yacute", # 235\n "yacute", # 236\n "Thorn", # 237\n "thorn", # 238\n "minus", # 239\n "multiply", # 240\n "onesuperior", # 241\n "twosuperior", # 242\n "threesuperior", # 243\n "onehalf", # 244\n "onequarter", # 245\n "threequarters", # 246\n "franc", # 247\n "Gbreve", # 248\n "gbreve", # 249\n "Idotaccent", # 250\n "Scedilla", # 251\n "scedilla", # 252\n "Cacute", # 253\n "cacute", # 254\n "Ccaron", # 255\n "ccaron", # 256\n "dcroat", # 257\n]\n
.venv\Lib\site-packages\fontTools\ttLib\standardGlyphOrder.py
standardGlyphOrder.py
Python
6,056
0.8
0.00369
0.037037
node-utils
562
2025-05-16T01:30:25.016595
GPL-3.0
false
8cd0375b16ca86f4b2a073a096d5a82b
from fontTools.ttLib.ttFont import TTFont\nfrom fontTools.ttLib.sfnt import readTTCHeader, writeTTCHeader\nfrom io import BytesIO\nimport struct\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\nclass TTCollection(object):\n """Object representing a TrueType Collection / OpenType Collection.\n The main API is self.fonts being a list of TTFont instances.\n\n If shareTables is True, then different fonts in the collection\n might point to the same table object if the data for the table was\n the same in the font file. Note, however, that this might result\n in suprises and incorrect behavior if the different fonts involved\n have different GlyphOrder. Use only if you know what you are doing.\n """\n\n def __init__(self, file=None, shareTables=False, **kwargs):\n fonts = self.fonts = []\n if file is None:\n return\n\n assert "fontNumber" not in kwargs, kwargs\n\n closeStream = False\n if not hasattr(file, "read"):\n file = open(file, "rb")\n closeStream = True\n\n tableCache = {} if shareTables else None\n\n header = readTTCHeader(file)\n for i in range(header.numFonts):\n font = TTFont(file, fontNumber=i, _tableCache=tableCache, **kwargs)\n fonts.append(font)\n\n # don't close file if lazy=True, as the TTFont hold a reference to the original\n # file; the file will be closed once the TTFonts are closed in the\n # TTCollection.close(). We still want to close the file if lazy is None or\n # False, because in that case the TTFont no longer need the original file\n # and we want to avoid 'ResourceWarning: unclosed file'.\n if not kwargs.get("lazy") and closeStream:\n file.close()\n\n def __enter__(self):\n return self\n\n def __exit__(self, type, value, traceback):\n self.close()\n\n def close(self):\n for font in self.fonts:\n font.close()\n\n def save(self, file, shareTables=True):\n """Save the font to disk. Similarly to the constructor,\n the 'file' argument can be either a pathname or a writable\n file object.\n """\n if not hasattr(file, "write"):\n final = None\n file = open(file, "wb")\n else:\n # assume "file" is a writable file object\n # write to a temporary stream to allow saving to unseekable streams\n final = file\n file = BytesIO()\n\n tableCache = {} if shareTables else None\n\n offsets_offset = writeTTCHeader(file, len(self.fonts))\n offsets = []\n for font in self.fonts:\n offsets.append(file.tell())\n font._save(file, tableCache=tableCache)\n file.seek(0, 2)\n\n file.seek(offsets_offset)\n file.write(struct.pack(">%dL" % len(self.fonts), *offsets))\n\n if final:\n final.write(file.getvalue())\n file.close()\n\n def saveXML(self, fileOrPath, newlinestr="\n", writeVersion=True, **kwargs):\n from fontTools.misc import xmlWriter\n\n writer = xmlWriter.XMLWriter(fileOrPath, newlinestr=newlinestr)\n\n if writeVersion:\n from fontTools import version\n\n version = ".".join(version.split(".")[:2])\n writer.begintag("ttCollection", ttLibVersion=version)\n else:\n writer.begintag("ttCollection")\n writer.newline()\n writer.newline()\n\n for font in self.fonts:\n font._saveXML(writer, writeVersion=False, **kwargs)\n writer.newline()\n\n writer.endtag("ttCollection")\n writer.newline()\n\n writer.close()\n\n def __getitem__(self, item):\n return self.fonts[item]\n\n def __setitem__(self, item, value):\n self.fonts[item] = value\n\n def __delitem__(self, item):\n return self.fonts[item]\n\n def __len__(self):\n return len(self.fonts)\n\n def __iter__(self):\n return iter(self.fonts)\n
.venv\Lib\site-packages\fontTools\ttLib\ttCollection.py
ttCollection.py
Python
4,088
0.95
0.24
0.073684
node-utils
953
2024-08-23T02:01:52.953580
MIT
false
c70ccfd250d876f8fe8e7e244743b70a
"""GlyphSets returned by a TTFont."""\n\nfrom abc import ABC, abstractmethod\nfrom collections.abc import Mapping\nfrom contextlib import contextmanager\nfrom copy import copy, deepcopy\nfrom types import SimpleNamespace\nfrom fontTools.misc.vector import Vector\nfrom fontTools.misc.fixedTools import otRound, fixedToFloat as fi2fl\nfrom fontTools.misc.loggingTools import deprecateFunction\nfrom fontTools.misc.transform import Transform, DecomposedTransform\nfrom fontTools.pens.transformPen import TransformPen, TransformPointPen\nfrom fontTools.pens.recordingPen import (\n DecomposingRecordingPen,\n lerpRecordings,\n replayRecording,\n)\n\n\nclass _TTGlyphSet(Mapping):\n """Generic dict-like GlyphSet class that pulls metrics from hmtx and\n glyph shape from TrueType or CFF.\n """\n\n def __init__(self, font, location, glyphsMapping, *, recalcBounds=True):\n self.recalcBounds = recalcBounds\n self.font = font\n self.defaultLocationNormalized = (\n {axis.axisTag: 0 for axis in self.font["fvar"].axes}\n if "fvar" in self.font\n else {}\n )\n self.location = location if location is not None else {}\n self.rawLocation = {} # VarComponent-only location\n self.originalLocation = location if location is not None else {}\n self.depth = 0\n self.locationStack = []\n self.rawLocationStack = []\n self.glyphsMapping = glyphsMapping\n self.hMetrics = font["hmtx"].metrics\n self.vMetrics = getattr(font.get("vmtx"), "metrics", None)\n self.hvarTable = None\n if location:\n from fontTools.varLib.varStore import VarStoreInstancer\n\n self.hvarTable = getattr(font.get("HVAR"), "table", None)\n if self.hvarTable is not None:\n self.hvarInstancer = VarStoreInstancer(\n self.hvarTable.VarStore, font["fvar"].axes, location\n )\n # TODO VVAR, VORG\n\n @contextmanager\n def pushLocation(self, location, reset: bool):\n self.locationStack.append(self.location)\n self.rawLocationStack.append(self.rawLocation)\n if reset:\n self.location = self.originalLocation.copy()\n self.rawLocation = self.defaultLocationNormalized.copy()\n else:\n self.location = self.location.copy()\n self.rawLocation = {}\n self.location.update(location)\n self.rawLocation.update(location)\n\n try:\n yield None\n finally:\n self.location = self.locationStack.pop()\n self.rawLocation = self.rawLocationStack.pop()\n\n @contextmanager\n def pushDepth(self):\n try:\n depth = self.depth\n self.depth += 1\n yield depth\n finally:\n self.depth -= 1\n\n def __contains__(self, glyphName):\n return glyphName in self.glyphsMapping\n\n def __iter__(self):\n return iter(self.glyphsMapping.keys())\n\n def __len__(self):\n return len(self.glyphsMapping)\n\n @deprecateFunction(\n "use 'glyphName in glyphSet' instead", category=DeprecationWarning\n )\n def has_key(self, glyphName):\n return glyphName in self.glyphsMapping\n\n\nclass _TTGlyphSetGlyf(_TTGlyphSet):\n def __init__(self, font, location, recalcBounds=True):\n self.glyfTable = font["glyf"]\n super().__init__(font, location, self.glyfTable, recalcBounds=recalcBounds)\n self.gvarTable = font.get("gvar")\n\n def __getitem__(self, glyphName):\n return _TTGlyphGlyf(self, glyphName, recalcBounds=self.recalcBounds)\n\n\nclass _TTGlyphSetCFF(_TTGlyphSet):\n def __init__(self, font, location):\n tableTag = "CFF2" if "CFF2" in font else "CFF "\n self.charStrings = list(font[tableTag].cff.values())[0].CharStrings\n super().__init__(font, location, self.charStrings)\n self.setLocation(location)\n\n def __getitem__(self, glyphName):\n return _TTGlyphCFF(self, glyphName)\n\n def setLocation(self, location):\n self.blender = None\n if location:\n # TODO Optimize by using instancer.setLocation()\n\n from fontTools.varLib.varStore import VarStoreInstancer\n\n varStore = getattr(self.charStrings, "varStore", None)\n if varStore is not None:\n instancer = VarStoreInstancer(\n varStore.otVarStore, self.font["fvar"].axes, location\n )\n self.blender = instancer.interpolateFromDeltas\n else:\n self.blender = None\n\n @contextmanager\n def pushLocation(self, location, reset: bool):\n self.setLocation(location)\n with _TTGlyphSet.pushLocation(self, location, reset) as value:\n try:\n yield value\n finally:\n self.setLocation(self.location)\n\n\nclass _TTGlyphSetVARC(_TTGlyphSet):\n def __init__(self, font, location, glyphSet):\n self.glyphSet = glyphSet\n super().__init__(font, location, glyphSet)\n self.varcTable = font["VARC"].table\n\n def __getitem__(self, glyphName):\n varc = self.varcTable\n if glyphName not in varc.Coverage.glyphs:\n return self.glyphSet[glyphName]\n return _TTGlyphVARC(self, glyphName)\n\n\nclass _TTGlyph(ABC):\n """Glyph object that supports the Pen protocol, meaning that it has\n .draw() and .drawPoints() methods that take a pen object as their only\n argument. Additionally there are 'width' and 'lsb' attributes, read from\n the 'hmtx' table.\n\n If the font contains a 'vmtx' table, there will also be 'height' and 'tsb'\n attributes.\n """\n\n def __init__(self, glyphSet, glyphName, *, recalcBounds=True):\n self.glyphSet = glyphSet\n self.name = glyphName\n self.recalcBounds = recalcBounds\n self.width, self.lsb = glyphSet.hMetrics[glyphName]\n if glyphSet.vMetrics is not None:\n self.height, self.tsb = glyphSet.vMetrics[glyphName]\n else:\n self.height, self.tsb = None, None\n if glyphSet.location and glyphSet.hvarTable is not None:\n varidx = (\n glyphSet.font.getGlyphID(glyphName)\n if glyphSet.hvarTable.AdvWidthMap is None\n else glyphSet.hvarTable.AdvWidthMap.mapping[glyphName]\n )\n self.width += glyphSet.hvarInstancer[varidx]\n # TODO: VVAR/VORG\n\n @abstractmethod\n def draw(self, pen):\n """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details\n how that works.\n """\n raise NotImplementedError\n\n def drawPoints(self, pen):\n """Draw the glyph onto ``pen``. See fontTools.pens.pointPen for details\n how that works.\n """\n from fontTools.pens.pointPen import SegmentToPointPen\n\n self.draw(SegmentToPointPen(pen))\n\n\nclass _TTGlyphGlyf(_TTGlyph):\n def draw(self, pen):\n """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details\n how that works.\n """\n glyph, offset = self._getGlyphAndOffset()\n\n with self.glyphSet.pushDepth() as depth:\n if depth:\n offset = 0 # Offset should only apply at top-level\n\n glyph.draw(pen, self.glyphSet.glyfTable, offset)\n\n def drawPoints(self, pen):\n """Draw the glyph onto ``pen``. See fontTools.pens.pointPen for details\n how that works.\n """\n glyph, offset = self._getGlyphAndOffset()\n\n with self.glyphSet.pushDepth() as depth:\n if depth:\n offset = 0 # Offset should only apply at top-level\n\n glyph.drawPoints(pen, self.glyphSet.glyfTable, offset)\n\n def _getGlyphAndOffset(self):\n if self.glyphSet.location and self.glyphSet.gvarTable is not None:\n glyph = self._getGlyphInstance()\n else:\n glyph = self.glyphSet.glyfTable[self.name]\n\n offset = self.lsb - glyph.xMin if hasattr(glyph, "xMin") else 0\n return glyph, offset\n\n def _getGlyphInstance(self):\n from fontTools.varLib.iup import iup_delta\n from fontTools.ttLib.tables._g_l_y_f import GlyphCoordinates\n from fontTools.varLib.models import supportScalar\n\n glyphSet = self.glyphSet\n glyfTable = glyphSet.glyfTable\n variations = glyphSet.gvarTable.variations[self.name]\n hMetrics = glyphSet.hMetrics\n vMetrics = glyphSet.vMetrics\n coordinates, _ = glyfTable._getCoordinatesAndControls(\n self.name, hMetrics, vMetrics\n )\n origCoords, endPts = None, None\n for var in variations:\n scalar = supportScalar(glyphSet.location, var.axes)\n if not scalar:\n continue\n delta = var.coordinates\n if None in delta:\n if origCoords is None:\n origCoords, control = glyfTable._getCoordinatesAndControls(\n self.name, hMetrics, vMetrics\n )\n endPts = (\n control[1] if control[0] >= 1 else list(range(len(control[1])))\n )\n delta = iup_delta(delta, origCoords, endPts)\n coordinates += GlyphCoordinates(delta) * scalar\n\n glyph = copy(glyfTable[self.name]) # Shallow copy\n width, lsb, height, tsb = _setCoordinates(\n glyph, coordinates, glyfTable, recalcBounds=self.recalcBounds\n )\n self.lsb = lsb\n self.tsb = tsb\n if glyphSet.hvarTable is None:\n # no HVAR: let's set metrics from the phantom points\n self.width = width\n self.height = height\n return glyph\n\n\nclass _TTGlyphCFF(_TTGlyph):\n def draw(self, pen):\n """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details\n how that works.\n """\n self.glyphSet.charStrings[self.name].draw(pen, self.glyphSet.blender)\n\n\ndef _evaluateCondition(condition, fvarAxes, location, instancer):\n if condition.Format == 1:\n # ConditionAxisRange\n axisIndex = condition.AxisIndex\n axisTag = fvarAxes[axisIndex].axisTag\n axisValue = location.get(axisTag, 0)\n minValue = condition.FilterRangeMinValue\n maxValue = condition.FilterRangeMaxValue\n return minValue <= axisValue <= maxValue\n elif condition.Format == 2:\n # ConditionValue\n value = condition.DefaultValue\n value += instancer[condition.VarIdx][0]\n return value > 0\n elif condition.Format == 3:\n # ConditionAnd\n for subcondition in condition.ConditionTable:\n if not _evaluateCondition(subcondition, fvarAxes, location, instancer):\n return False\n return True\n elif condition.Format == 4:\n # ConditionOr\n for subcondition in condition.ConditionTable:\n if _evaluateCondition(subcondition, fvarAxes, location, instancer):\n return True\n return False\n elif condition.Format == 5:\n # ConditionNegate\n return not _evaluateCondition(\n condition.conditionTable, fvarAxes, location, instancer\n )\n else:\n return False # Unkonwn condition format\n\n\nclass _TTGlyphVARC(_TTGlyph):\n def _draw(self, pen, isPointPen):\n """Draw the glyph onto ``pen``. See fontTools.pens.basePen for details\n how that works.\n """\n from fontTools.ttLib.tables.otTables import (\n VarComponentFlags,\n NO_VARIATION_INDEX,\n )\n\n glyphSet = self.glyphSet\n varc = glyphSet.varcTable\n idx = varc.Coverage.glyphs.index(self.name)\n glyph = varc.VarCompositeGlyphs.VarCompositeGlyph[idx]\n\n from fontTools.varLib.multiVarStore import MultiVarStoreInstancer\n from fontTools.varLib.varStore import VarStoreInstancer\n\n fvarAxes = glyphSet.font["fvar"].axes\n instancer = MultiVarStoreInstancer(\n varc.MultiVarStore, fvarAxes, self.glyphSet.location\n )\n\n for comp in glyph.components:\n if comp.flags & VarComponentFlags.HAVE_CONDITION:\n condition = varc.ConditionList.ConditionTable[comp.conditionIndex]\n if not _evaluateCondition(\n condition, fvarAxes, self.glyphSet.location, instancer\n ):\n continue\n\n location = {}\n if comp.axisIndicesIndex is not None:\n axisIndices = varc.AxisIndicesList.Item[comp.axisIndicesIndex]\n axisValues = Vector(comp.axisValues)\n if comp.axisValuesVarIndex != NO_VARIATION_INDEX:\n axisValues += fi2fl(instancer[comp.axisValuesVarIndex], 14)\n assert len(axisIndices) == len(axisValues), (\n len(axisIndices),\n len(axisValues),\n )\n location = {\n fvarAxes[i].axisTag: v for i, v in zip(axisIndices, axisValues)\n }\n\n if comp.transformVarIndex != NO_VARIATION_INDEX:\n deltas = instancer[comp.transformVarIndex]\n comp = deepcopy(comp)\n comp.applyTransformDeltas(deltas)\n transform = comp.transform\n\n reset = comp.flags & VarComponentFlags.RESET_UNSPECIFIED_AXES\n with self.glyphSet.glyphSet.pushLocation(location, reset):\n with self.glyphSet.pushLocation(location, reset):\n shouldDecompose = self.name == comp.glyphName\n\n if not shouldDecompose:\n try:\n pen.addVarComponent(\n comp.glyphName, transform, self.glyphSet.rawLocation\n )\n except AttributeError:\n shouldDecompose = True\n\n if shouldDecompose:\n t = transform.toTransform()\n compGlyphSet = (\n self.glyphSet\n if comp.glyphName != self.name\n else glyphSet.glyphSet\n )\n g = compGlyphSet[comp.glyphName]\n if isPointPen:\n tPen = TransformPointPen(pen, t)\n g.drawPoints(tPen)\n else:\n tPen = TransformPen(pen, t)\n g.draw(tPen)\n\n def draw(self, pen):\n self._draw(pen, False)\n\n def drawPoints(self, pen):\n self._draw(pen, True)\n\n\ndef _setCoordinates(glyph, coord, glyfTable, *, recalcBounds=True):\n # Handle phantom points for (left, right, top, bottom) positions.\n assert len(coord) >= 4\n leftSideX = coord[-4][0]\n rightSideX = coord[-3][0]\n topSideY = coord[-2][1]\n bottomSideY = coord[-1][1]\n\n for _ in range(4):\n del coord[-1]\n\n if glyph.isComposite():\n assert len(coord) == len(glyph.components)\n glyph.components = [copy(comp) for comp in glyph.components] # Shallow copy\n for p, comp in zip(coord, glyph.components):\n if hasattr(comp, "x"):\n comp.x, comp.y = p\n elif glyph.numberOfContours == 0:\n assert len(coord) == 0\n else:\n assert len(coord) == len(glyph.coordinates)\n glyph.coordinates = coord\n\n if recalcBounds:\n glyph.recalcBounds(glyfTable)\n\n horizontalAdvanceWidth = otRound(rightSideX - leftSideX)\n verticalAdvanceWidth = otRound(topSideY - bottomSideY)\n leftSideBearing = otRound(glyph.xMin - leftSideX)\n topSideBearing = otRound(topSideY - glyph.yMax)\n return (\n horizontalAdvanceWidth,\n leftSideBearing,\n verticalAdvanceWidth,\n topSideBearing,\n )\n\n\nclass LerpGlyphSet(Mapping):\n """A glyphset that interpolates between two other glyphsets.\n\n Factor is typically between 0 and 1. 0 means the first glyphset,\n 1 means the second glyphset, and 0.5 means the average of the\n two glyphsets. Other values are possible, and can be useful to\n extrapolate. Defaults to 0.5.\n """\n\n def __init__(self, glyphset1, glyphset2, factor=0.5):\n self.glyphset1 = glyphset1\n self.glyphset2 = glyphset2\n self.factor = factor\n\n def __getitem__(self, glyphname):\n if glyphname in self.glyphset1 and glyphname in self.glyphset2:\n return LerpGlyph(glyphname, self)\n raise KeyError(glyphname)\n\n def __contains__(self, glyphname):\n return glyphname in self.glyphset1 and glyphname in self.glyphset2\n\n def __iter__(self):\n set1 = set(self.glyphset1)\n set2 = set(self.glyphset2)\n return iter(set1.intersection(set2))\n\n def __len__(self):\n set1 = set(self.glyphset1)\n set2 = set(self.glyphset2)\n return len(set1.intersection(set2))\n\n\nclass LerpGlyph:\n def __init__(self, glyphname, glyphset):\n self.glyphset = glyphset\n self.glyphname = glyphname\n\n def draw(self, pen):\n recording1 = DecomposingRecordingPen(self.glyphset.glyphset1)\n self.glyphset.glyphset1[self.glyphname].draw(recording1)\n recording2 = DecomposingRecordingPen(self.glyphset.glyphset2)\n self.glyphset.glyphset2[self.glyphname].draw(recording2)\n\n factor = self.glyphset.factor\n\n replayRecording(lerpRecordings(recording1.value, recording2.value, factor), pen)\n
.venv\Lib\site-packages\fontTools\ttLib\ttGlyphSet.py
ttGlyphSet.py
Python
17,966
0.95
0.212245
0.02439
vue-tools
693
2025-03-07T19:25:32.139769
BSD-3-Clause
false
29ed445b41f00cb0f29350a62e41c633
"""Specialization of fontTools.misc.visitor to work with TTFont."""\n\nfrom fontTools.misc.visitor import Visitor\nfrom fontTools.ttLib import TTFont\n\n\nclass TTVisitor(Visitor):\n def visitAttr(self, obj, attr, value, *args, **kwargs):\n if isinstance(value, TTFont):\n return False\n super().visitAttr(obj, attr, value, *args, **kwargs)\n\n def visit(self, obj, *args, **kwargs):\n if hasattr(obj, "ensureDecompiled"):\n obj.ensureDecompiled(recurse=False)\n super().visit(obj, *args, **kwargs)\n\n\n@TTVisitor.register(TTFont)\ndef visit(visitor, font, *args, **kwargs):\n # Some objects have links back to TTFont; even though we\n # have a check in visitAttr to stop them from recursing\n # onto TTFont, sometimes they still do, for example when\n # someone overrides visitAttr.\n if hasattr(visitor, "font"):\n return False\n\n visitor.font = font\n for tag in font.keys():\n visitor.visit(font[tag], *args, **kwargs)\n del visitor.font\n return False\n
.venv\Lib\site-packages\fontTools\ttLib\ttVisitor.py
ttVisitor.py
Python
1,057
0.95
0.28125
0.16
awesome-app
689
2025-02-19T07:54:11.551334
GPL-3.0
false
b101ae2c3689ba03106ae3bb869ca0a3
"""fontTools.ttLib -- a package for dealing with TrueType fonts."""\n\nfrom fontTools.config import OPTIONS\nfrom fontTools.misc.loggingTools import deprecateFunction\nimport logging\n\n\nlog = logging.getLogger(__name__)\n\n\nOPTIMIZE_FONT_SPEED = OPTIONS["fontTools.ttLib:OPTIMIZE_FONT_SPEED"]\n\n\nclass TTLibError(Exception):\n pass\n\n\nclass TTLibFileIsCollectionError(TTLibError):\n pass\n\n\n@deprecateFunction("use logging instead", category=DeprecationWarning)\ndef debugmsg(msg):\n import time\n\n print(msg + time.strftime(" (%H:%M:%S)", time.localtime(time.time())))\n\n\nfrom fontTools.ttLib.ttFont import *\nfrom fontTools.ttLib.ttCollection import TTCollection\n
.venv\Lib\site-packages\fontTools\ttLib\__init__.py
__init__.py
Python
691
0.85
0.133333
0
vue-tools
425
2023-09-07T15:49:35.874577
MIT
false
c82ad43d2375a7729162726b6f1a0dfb
import sys\nfrom fontTools.ttLib import OPTIMIZE_FONT_SPEED, TTLibError, TTLibFileIsCollectionError\nfrom fontTools.ttLib.ttFont import *\nfrom fontTools.ttLib.ttCollection import TTCollection\n\n\ndef main(args=None):\n """Open/save fonts with TTFont() or TTCollection()\n\n ./fonttools ttLib [-oFILE] [-yNUMBER] files...\n\n If multiple files are given on the command-line,\n they are each opened (as a font or collection),\n and added to the font list.\n\n If -o (output-file) argument is given, the font\n list is then saved to the output file, either as\n a single font, if there is only one font, or as\n a collection otherwise.\n\n If -y (font-number) argument is given, only the\n specified font from collections is opened.\n\n The above allow extracting a single font from a\n collection, or combining multiple fonts into a\n collection.\n\n If --lazy or --no-lazy are give, those are passed\n to the TTFont() or TTCollection() constructors.\n """\n from fontTools import configLogger\n\n if args is None:\n args = sys.argv[1:]\n\n import argparse\n\n parser = argparse.ArgumentParser(\n "fonttools ttLib",\n description="Open/save fonts with TTFont() or TTCollection()",\n epilog="""\n If multiple files are given on the command-line,\n they are each opened (as a font or collection),\n and added to the font list.\n\n The above, when combined with -o / --output,\n allows for extracting a single font from a\n collection, or combining multiple fonts into a\n collection.\n """,\n )\n parser.add_argument("font", metavar="font", nargs="*", help="Font file.")\n parser.add_argument(\n "-t", "--table", metavar="table", action="append", help="Tables to decompile."\n )\n parser.add_argument(\n "-o", "--output", metavar="FILE", default=None, help="Output file."\n )\n parser.add_argument(\n "-y", metavar="NUMBER", default=-1, help="Font number to load from collections."\n )\n parser.add_argument(\n "--lazy", action="store_true", default=None, help="Load fonts lazily."\n )\n parser.add_argument(\n "--no-lazy", dest="lazy", action="store_false", help="Load fonts immediately."\n )\n parser.add_argument(\n "--flavor",\n dest="flavor",\n default=None,\n help="Flavor of output font. 'woff' or 'woff2'.",\n )\n parser.add_argument(\n "--no-recalc-timestamp",\n dest="recalcTimestamp",\n action="store_false",\n help="Keep the original font 'modified' timestamp.",\n )\n parser.add_argument(\n "-b",\n dest="recalcBBoxes",\n action="store_false",\n help="Don't recalc glyph bounding boxes: use the values in the original font.",\n )\n parser.add_argument(\n "--optimize-font-speed",\n action="store_true",\n help=(\n "Enable optimizations that prioritize speed over file size. This "\n "mainly affects how glyf table and gvar / VARC tables are compiled."\n ),\n )\n options = parser.parse_args(args)\n\n fontNumber = int(options.y) if options.y is not None else None\n outFile = options.output\n lazy = options.lazy\n flavor = options.flavor\n tables = options.table\n recalcBBoxes = options.recalcBBoxes\n recalcTimestamp = options.recalcTimestamp\n optimizeFontSpeed = options.optimize_font_speed\n\n fonts = []\n for f in options.font:\n try:\n font = TTFont(\n f,\n recalcBBoxes=recalcBBoxes,\n recalcTimestamp=recalcTimestamp,\n fontNumber=fontNumber,\n lazy=lazy,\n )\n if optimizeFontSpeed:\n font.cfg[OPTIMIZE_FONT_SPEED] = optimizeFontSpeed\n fonts.append(font)\n except TTLibFileIsCollectionError:\n collection = TTCollection(f, lazy=lazy)\n fonts.extend(collection.fonts)\n\n if tables is None:\n if lazy is False:\n tables = ["*"]\n elif optimizeFontSpeed:\n tables = {"glyf", "gvar", "VARC"}.intersection(font.keys())\n else:\n tables = []\n for font in fonts:\n if "GlyphOrder" in tables:\n font.getGlyphOrder()\n for table in tables if "*" not in tables else font.keys():\n font[table] # Decompiles\n\n if outFile is not None:\n if len(fonts) == 1:\n fonts[0].flavor = flavor\n fonts[0].save(outFile)\n else:\n if flavor is not None:\n raise TTLibError("Cannot set flavor for collections.")\n collection = TTCollection()\n collection.fonts = fonts\n collection.save(outFile)\n\n\nif __name__ == "__main__":\n sys.exit(main())\n
.venv\Lib\site-packages\fontTools\ttLib\__main__.py
__main__.py
Python
4,881
0.95
0.128378
0
python-kit
301
2023-12-31T20:02:59.922881
MIT
false
d9550f6e6f427eb2f9ed36d6a51d8625
from fontTools.misc.textTools import strjoin, tobytes, tostr\nfrom . import DefaultTable\n\n\nclass asciiTable(DefaultTable.DefaultTable):\n def toXML(self, writer, ttFont):\n data = tostr(self.data)\n # removing null bytes. XXX needed??\n data = data.split("\0")\n data = strjoin(data)\n writer.begintag("source")\n writer.newline()\n writer.write_noindent(data)\n writer.newline()\n writer.endtag("source")\n writer.newline()\n\n def fromXML(self, name, attrs, content, ttFont):\n lines = strjoin(content).split("\n")\n self.data = tobytes("\n".join(lines[1:-1]))\n
.venv\Lib\site-packages\fontTools\ttLib\tables\asciiTable.py
asciiTable.py
Python
657
0.95
0.15
0.058824
awesome-app
527
2023-08-10T22:05:50.028447
Apache-2.0
false
3e8132d67a2dae1e0f4089316c91b96d
from fontTools.misc.textTools import Tag\nfrom fontTools.ttLib import getClassTag\n\n\nclass DefaultTable(object):\n dependencies = []\n\n def __init__(self, tag=None):\n if tag is None:\n tag = getClassTag(self.__class__)\n self.tableTag = Tag(tag)\n\n def decompile(self, data, ttFont):\n self.data = data\n\n def compile(self, ttFont):\n return self.data\n\n def toXML(self, writer, ttFont, **kwargs):\n if hasattr(self, "ERROR"):\n writer.comment("An error occurred during the decompilation of this table")\n writer.newline()\n writer.comment(self.ERROR)\n writer.newline()\n writer.begintag("hexdata")\n writer.newline()\n writer.dumphex(self.compile(ttFont))\n writer.endtag("hexdata")\n writer.newline()\n\n def fromXML(self, name, attrs, content, ttFont):\n from fontTools.misc.textTools import readHex\n from fontTools import ttLib\n\n if name != "hexdata":\n raise ttLib.TTLibError("can't handle '%s' element" % name)\n self.decompile(readHex(content), ttFont)\n\n def __repr__(self):\n return "<'%s' table at %x>" % (self.tableTag, id(self))\n\n def __eq__(self, other):\n if type(self) != type(other):\n return NotImplemented\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n result = self.__eq__(other)\n return result if result is NotImplemented else not result\n
.venv\Lib\site-packages\fontTools\ttLib\tables\DefaultTable.py
DefaultTable.py
Python
1,536
0.85
0.285714
0
vue-tools
245
2025-04-28T06:37:10.842803
GPL-3.0
false
eb082b80bf532dab11e9edb8ccd54632
import json\nfrom textwrap import indent\n\nfrom . import DefaultTable\nfrom fontTools.misc.textTools import tostr\n\n\nclass table_D__e_b_g(DefaultTable.DefaultTable):\n def __init__(self, tag=None):\n DefaultTable.DefaultTable.__init__(self, tag)\n self.data = {}\n\n def decompile(self, data, ttFont):\n self.data = json.loads(data)\n\n def compile(self, ttFont):\n return json.dumps(self.data).encode("utf-8")\n\n def toXML(self, writer, ttFont):\n # make sure json indentation inside CDATA block matches XMLWriter's\n data = json.dumps(self.data, indent=len(writer.indentwhite))\n prefix = tostr(writer.indentwhite) * (writer.indentlevel + 1)\n # but don't indent the first json line so it's adjacent to `<![CDATA[{`\n cdata = indent(data, prefix, lambda ln: ln != "{\n")\n\n writer.begintag("json")\n writer.newline()\n writer.writecdata(cdata)\n writer.newline()\n writer.endtag("json")\n writer.newline()\n\n def fromXML(self, name, attrs, content, ttFont):\n if name == "json":\n self.data = json.loads("".join(content))\n
.venv\Lib\site-packages\fontTools\ttLib\tables\D__e_b_g.py
D__e_b_g.py
Python
1,169
0.95
0.2
0.074074
vue-tools
420
2023-08-27T08:15:54.304295
MIT
false
9ec6cbe01e7f541df59834453eb28a43