code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def build(self):
"""Build the lookup.
Returns:
An ``otTables.Lookup`` object representing the pair positioning
lookup.
"""
builders = {}
builder = ClassPairPosSubtableBuilder(self)
for glyphclass1, value1, glyphclass2, value2 in self.pairs:
... | Build the lookup.
Returns:
An ``otTables.Lookup`` object representing the pair positioning
lookup.
| build | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def add_pos(self, location, glyph, otValueRecord):
"""Add a single positioning rule.
Args:
location: A string or tuple representing the location in the
original source which produced this lookup.
glyph: A glyph name.
otValueRection: A ``otTables.Value... | Add a single positioning rule.
Args:
location: A string or tuple representing the location in the
original source which produced this lookup.
glyph: A glyph name.
otValueRection: A ``otTables.ValueRecord`` used to position the
glyph.
| add_pos | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildSingleSubstSubtable(mapping):
"""Builds a single substitution (GSUB1) subtable.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.SingleSubstBuilder` instead.
Args:
mapping: A dictionary mapping inp... | Builds a single substitution (GSUB1) subtable.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.SingleSubstBuilder` instead.
Args:
mapping: A dictionary mapping input glyph names to output glyph names.
Ret... | buildSingleSubstSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildMultipleSubstSubtable(mapping):
"""Builds a multiple substitution (GSUB2) subtable.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead.
Example::
# sub uni06C0 by uni06... | Builds a multiple substitution (GSUB2) subtable.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.MultipleSubstBuilder` instead.
Example::
# sub uni06C0 by uni06D5.fina hamza.above
# sub uni06C2 by uni... | buildMultipleSubstSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildAlternateSubstSubtable(mapping):
"""Builds an alternate substitution (GSUB3) subtable.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead.
Args:
mapping: A dictionary m... | Builds an alternate substitution (GSUB3) subtable.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.AlternateSubstBuilder` instead.
Args:
mapping: A dictionary mapping input glyph names to a list of output
... | buildAlternateSubstSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildLigatureSubstSubtable(mapping):
"""Builds a ligature substitution (GSUB4) subtable.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead.
Example::
# sub f f i by f_f_i;
... | Builds a ligature substitution (GSUB4) subtable.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.LigatureSubstBuilder` instead.
Example::
# sub f f i by f_f_i;
# sub f i by f_i;
subtable = bu... | buildLigatureSubstSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildAnchor(x, y, point=None, deviceX=None, deviceY=None):
"""Builds an Anchor table.
This determines the appropriate anchor format based on the passed parameters.
Args:
x (int): X coordinate.
y (int): Y coordinate.
point (int): Index of glyph contour point, if provided.
... | Builds an Anchor table.
This determines the appropriate anchor format based on the passed parameters.
Args:
x (int): X coordinate.
y (int): Y coordinate.
point (int): Index of glyph contour point, if provided.
deviceX (``otTables.Device``): X coordinate device table, if provide... | buildAnchor | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildBaseArray(bases, numMarkClasses, glyphMap):
"""Builds a base array record.
As part of building mark-to-base positioning rules, you will need to define
a ``BaseArray`` record, which "defines for each base glyph an array of
anchors, one for each mark class." This function builds the base array
... | Builds a base array record.
As part of building mark-to-base positioning rules, you will need to define
a ``BaseArray`` record, which "defines for each base glyph an array of
anchors, one for each mark class." This function builds the base array
subtable.
Example::
bases = {"a": {0: a3, 1... | buildBaseArray | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildComponentRecord(anchors):
"""Builds a component record.
As part of building mark-to-ligature positioning rules, you will need to
define ``ComponentRecord`` objects, which contain "an array of offsets...
to the Anchor tables that define all the attachment points used to attach
marks to the ... | Builds a component record.
As part of building mark-to-ligature positioning rules, you will need to
define ``ComponentRecord`` objects, which contain "an array of offsets...
to the Anchor tables that define all the attachment points used to attach
marks to the component." This function builds the compo... | buildComponentRecord | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildCursivePosSubtable(attach, glyphMap):
"""Builds a cursive positioning (GPOS3) subtable.
Cursive positioning lookups are made up of a coverage table of glyphs,
and a set of ``EntryExitRecord`` records containing the anchors for
each glyph. This function builds the cursive positioning subtable.
... | Builds a cursive positioning (GPOS3) subtable.
Cursive positioning lookups are made up of a coverage table of glyphs,
and a set of ``EntryExitRecord`` records containing the anchors for
each glyph. This function builds the cursive positioning subtable.
Example::
subtable = buildCursivePosSubt... | buildCursivePosSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildDevice(deltas):
"""Builds a Device record as part of a ValueRecord or Anchor.
Device tables specify size-specific adjustments to value records
and anchors to reflect changes based on the resolution of the output.
For example, one could specify that an anchor's Y position should be
increase... | Builds a Device record as part of a ValueRecord or Anchor.
Device tables specify size-specific adjustments to value records
and anchors to reflect changes based on the resolution of the output.
For example, one could specify that an anchor's Y position should be
increased by 1 pixel when displayed at 8... | buildDevice | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildLigatureArray(ligs, numMarkClasses, glyphMap):
"""Builds a LigatureArray subtable.
As part of building a mark-to-ligature lookup, you will need to define
the set of anchors (for each mark class) on each component of the ligature
where marks can be attached. For example, for an Arabic divine na... | Builds a LigatureArray subtable.
As part of building a mark-to-ligature lookup, you will need to define
the set of anchors (for each mark class) on each component of the ligature
where marks can be attached. For example, for an Arabic divine name ligature
(lam lam heh), you may want to specify mark att... | buildLigatureArray | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildMarkArray(marks, glyphMap):
"""Builds a mark array subtable.
As part of building mark-to-* positioning rules, you will need to define
a MarkArray subtable, which "defines the class and the anchor point
for a mark glyph." This function builds the mark array subtable.
Example::
mar... | Builds a mark array subtable.
As part of building mark-to-* positioning rules, you will need to define
a MarkArray subtable, which "defines the class and the anchor point
for a mark glyph." This function builds the mark array subtable.
Example::
mark = {
"acute": (0, buildAnchor(3... | buildMarkArray | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildMarkBasePosSubtable(marks, bases, glyphMap):
"""Build a single MarkBasePos (GPOS4) subtable.
This builds a mark-to-base lookup subtable containing all of the referenced
marks and bases.
Example::
# a1, a2, a3, a4, a5 = buildAnchor(500, 100), ...
marks = {"acute": (0, a1), "g... | Build a single MarkBasePos (GPOS4) subtable.
This builds a mark-to-base lookup subtable containing all of the referenced
marks and bases.
Example::
# a1, a2, a3, a4, a5 = buildAnchor(500, 100), ...
marks = {"acute": (0, a1), "grave": (0, a1), "cedilla": (1, a2)}
bases = {"a": {0:... | buildMarkBasePosSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildMarkLigPosSubtable(marks, ligs, glyphMap):
"""Build a single MarkLigPos (GPOS5) subtable.
This builds a mark-to-base lookup subtable containing all of the referenced
marks and bases.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`f... | Build a single MarkLigPos (GPOS5) subtable.
This builds a mark-to-base lookup subtable containing all of the referenced
marks and bases.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.lookupBuilders.MarkLigPosBuilder` instead.
... | buildMarkLigPosSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildPairPosGlyphs(pairs, glyphMap):
"""Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables.
This organises a list of pair positioning adjustments into subtables based
on common value record formats.
Note that if you are implementing a layout compiler, you may find it more
... | Builds a list of glyph-based pair adjustment (GPOS2 format 1) subtables.
This organises a list of pair positioning adjustments into subtables based
on common value record formats.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:py:class:`fontTools.otlLib.... | buildPairPosGlyphs | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildPairPosGlyphsSubtable(pairs, glyphMap, valueFormat1=None, valueFormat2=None):
"""Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable.
This builds a PairPos subtable from a dictionary of glyph pairs and
their positioning adjustments. See also :func:`buildPairPosGlyphs`.
Note ... | Builds a single glyph-based pair adjustment (GPOS2 format 1) subtable.
This builds a PairPos subtable from a dictionary of glyph pairs and
their positioning adjustments. See also :func:`buildPairPosGlyphs`.
Note that if you are implementing a layout compiler, you may find it more
flexible to use
:... | buildPairPosGlyphsSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildSinglePos(mapping, glyphMap):
"""Builds a list of single adjustment (GPOS1) subtables.
This builds a list of SinglePos subtables from a dictionary of glyph
names and their positioning adjustments. The format of the subtables are
determined to optimize the size of the resulting subtables.
S... | Builds a list of single adjustment (GPOS1) subtables.
This builds a list of SinglePos subtables from a dictionary of glyph
names and their positioning adjustments. The format of the subtables are
determined to optimize the size of the resulting subtables.
See also :func:`buildSinglePosSubtable`.
N... | buildSinglePos | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildSinglePosSubtable(values, glyphMap):
"""Builds a single adjustment (GPOS1) subtable.
This builds a list of SinglePos subtables from a dictionary of glyph
names and their positioning adjustments. The format of the subtable is
determined to optimize the size of the output.
See also :func:`bu... | Builds a single adjustment (GPOS1) subtable.
This builds a list of SinglePos subtables from a dictionary of glyph
names and their positioning adjustments. The format of the subtable is
determined to optimize the size of the output.
See also :func:`buildSinglePos`.
Note that if you are implementing... | buildSinglePosSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildValue(value):
"""Builds a positioning value record.
Value records are used to specify coordinates and adjustments for
positioning and attaching glyphs. Many of the positioning functions
in this library take ``otTables.ValueRecord`` objects as arguments.
This function builds value records f... | Builds a positioning value record.
Value records are used to specify coordinates and adjustments for
positioning and attaching glyphs. Many of the positioning functions
in this library take ``otTables.ValueRecord`` objects as arguments.
This function builds value records from dictionaries.
Args:
... | buildValue | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildAttachList(attachPoints, glyphMap):
"""Builds an AttachList subtable.
A GDEF table may contain an Attachment Point List table (AttachList)
which stores the contour indices of attachment points for glyphs with
attachment points. This routine builds AttachList subtables.
Args:
attac... | Builds an AttachList subtable.
A GDEF table may contain an Attachment Point List table (AttachList)
which stores the contour indices of attachment points for glyphs with
attachment points. This routine builds AttachList subtables.
Args:
attachPoints (dict): A mapping between glyph names and a ... | buildAttachList | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildLigCaretList(coords, points, glyphMap):
"""Builds a ligature caret list table.
Ligatures appear as a single glyph representing multiple characters; however
when, for example, editing text containing a ``f_i`` ligature, the user may
want to place the cursor between the ``f`` and the ``i``. The ... | Builds a ligature caret list table.
Ligatures appear as a single glyph representing multiple characters; however
when, for example, editing text containing a ``f_i`` ligature, the user may
want to place the cursor between the ``f`` and the ``i``. The ligature caret
list in the GDEF table specifies the ... | buildLigCaretList | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def buildMarkGlyphSetsDef(markSets, glyphMap):
"""Builds a mark glyph sets definition table.
OpenType Layout lookups may choose to use mark filtering sets to consider
or ignore particular combinations of marks. These sets are specified by
setting a flag on the lookup, but the mark filtering sets are de... | Builds a mark glyph sets definition table.
OpenType Layout lookups may choose to use mark filtering sets to consider
or ignore particular combinations of marks. These sets are specified by
setting a flag on the lookup, but the mark filtering sets are defined in
the ``GDEF`` table. This routine builds t... | buildMarkGlyphSetsDef | python | fonttools/fonttools | Lib/fontTools/otlLib/builder.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/builder.py | MIT |
def maxCtxFont(font):
"""Calculate the usMaxContext value for an entire font."""
maxCtx = 0
for tag in ("GSUB", "GPOS"):
if tag not in font:
continue
table = font[tag].table
if not table.LookupList:
continue
for lookup in table.LookupList.Lookup:
... | Calculate the usMaxContext value for an entire font. | maxCtxFont | python | fonttools/fonttools | Lib/fontTools/otlLib/maxContextCalc.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/maxContextCalc.py | MIT |
def maxCtxSubtable(maxCtx, tag, lookupType, st):
"""Calculate usMaxContext based on a single lookup table (and an existing
max value).
"""
# single positioning, single / multiple substitution
if (tag == "GPOS" and lookupType == 1) or (
tag == "GSUB" and lookupType in (1, 2, 3)
):
... | Calculate usMaxContext based on a single lookup table (and an existing
max value).
| maxCtxSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/maxContextCalc.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/maxContextCalc.py | MIT |
def maxCtxContextualSubtable(maxCtx, st, ruleType, chain=""):
"""Calculate usMaxContext based on a contextual feature subtable."""
if st.Format == 1:
for ruleset in getattr(st, "%s%sRuleSet" % (chain, ruleType)):
if ruleset is None:
continue
for rule in getattr(r... | Calculate usMaxContext based on a contextual feature subtable. | maxCtxContextualSubtable | python | fonttools/fonttools | Lib/fontTools/otlLib/maxContextCalc.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/maxContextCalc.py | MIT |
def maxCtxContextualRule(maxCtx, st, chain):
"""Calculate usMaxContext based on a contextual feature rule."""
if not chain:
return max(maxCtx, st.GlyphCount)
elif chain == "Reverse":
return max(maxCtx, 1 + st.LookAheadGlyphCount)
return max(maxCtx, st.InputGlyphCount + st.LookAheadGlyph... | Calculate usMaxContext based on a contextual feature rule. | maxCtxContextualRule | python | fonttools/fonttools | Lib/fontTools/otlLib/maxContextCalc.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/maxContextCalc.py | MIT |
def main(args=None):
"""Optimize the layout tables of an existing font"""
from argparse import ArgumentParser
from fontTools import configLogger
parser = ArgumentParser(
prog="otlLib.optimize",
description=main.__doc__,
formatter_class=RawTextHelpFormatter,
)
parser.add... | Optimize the layout tables of an existing font | main | python | fonttools/fonttools | Lib/fontTools/otlLib/optimize/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/otlLib/optimize/__init__.py | MIT |
def addComponent(
self,
glyphName: str,
transformation: Tuple[float, float, float, float, float, float],
) -> None:
"""Add a sub glyph. The 'transformation' argument must be a 6-tuple
containing an affine transformation, or a Transform object from the
fontTools.misc.t... | Add a sub glyph. The 'transformation' argument must be a 6-tuple
containing an affine transformation, or a Transform object from the
fontTools.misc.transform module. More precisely: it should be a
sequence containing 6 numbers.
| addComponent | python | fonttools/fonttools | Lib/fontTools/pens/basePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py | MIT |
def addVarComponent(
self,
glyphName: str,
transformation: DecomposedTransform,
location: Dict[str, float],
) -> None:
"""Add a VarComponent sub glyph. The 'transformation' argument
must be a DecomposedTransform from the fontTools.misc.transform module,
and th... | Add a VarComponent sub glyph. The 'transformation' argument
must be a DecomposedTransform from the fontTools.misc.transform module,
and the 'location' argument must be a dictionary mapping axis tags
to their locations.
| addVarComponent | python | fonttools/fonttools | Lib/fontTools/pens/basePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py | MIT |
def __init__(
self,
glyphSet,
*args,
skipMissingComponents=None,
reverseFlipped=False,
**kwargs,
):
"""Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced
as components are looked up by their name.
If the optional 'reve... | Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced
as components are looked up by their name.
If the optional 'reverseFlipped' argument is True, components whose transformation
matrix has a negative determinant will be decomposed with a reversed path direction
t... | __init__ | python | fonttools/fonttools | Lib/fontTools/pens/basePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py | MIT |
def addComponent(self, glyphName, transformation):
"""Transform the points of the base glyph and draw it onto self."""
from fontTools.pens.transformPen import TransformPen
try:
glyph = self.glyphSet[glyphName]
except KeyError:
if not self.skipMissingComponents:
... | Transform the points of the base glyph and draw it onto self. | addComponent | python | fonttools/fonttools | Lib/fontTools/pens/basePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py | MIT |
def _qCurveToOne(self, pt1, pt2):
"""This method implements the basic quadratic curve type. The
default implementation delegates the work to the cubic curve
function. Optionally override with a native implementation.
"""
pt0x, pt0y = self.__currentPoint
pt1x, pt1y = pt1
... | This method implements the basic quadratic curve type. The
default implementation delegates the work to the cubic curve
function. Optionally override with a native implementation.
| _qCurveToOne | python | fonttools/fonttools | Lib/fontTools/pens/basePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py | MIT |
def decomposeSuperBezierSegment(points):
"""Split the SuperBezier described by 'points' into a list of regular
bezier segments. The 'points' argument must be a sequence with length
3 or greater, containing (x, y) coordinates. The last point is the
destination on-curve point, the rest of the points are o... | Split the SuperBezier described by 'points' into a list of regular
bezier segments. The 'points' argument must be a sequence with length
3 or greater, containing (x, y) coordinates. The last point is the
destination on-curve point, the rest of the points are off-curve points.
The start point should not ... | decomposeSuperBezierSegment | python | fonttools/fonttools | Lib/fontTools/pens/basePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py | MIT |
def decomposeQuadraticSegment(points):
"""Split the quadratic curve segment described by 'points' into a list
of "atomic" quadratic segments. The 'points' argument must be a sequence
with length 2 or greater, containing (x, y) coordinates. The last point
is the destination on-curve point, the rest of th... | Split the quadratic curve segment described by 'points' into a list
of "atomic" quadratic segments. The 'points' argument must be a sequence
with length 2 or greater, containing (x, y) coordinates. The last point
is the destination on-curve point, the rest of the points are off-curve
points. The start p... | decomposeQuadraticSegment | python | fonttools/fonttools | Lib/fontTools/pens/basePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/basePen.py | MIT |
def outline(self, transform=None, evenOdd=False):
"""Converts the current contours to ``FT_Outline``.
Args:
transform: An optional 6-tuple containing an affine transformation,
or a ``Transform`` object from the ``fontTools.misc.transform``
module.
... | Converts the current contours to ``FT_Outline``.
Args:
transform: An optional 6-tuple containing an affine transformation,
or a ``Transform`` object from the ``fontTools.misc.transform``
module.
evenOdd: Pass ``True`` for even-odd fill instead of non-zero... | outline | python | fonttools/fonttools | Lib/fontTools/pens/freetypePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/freetypePen.py | MIT |
def bbox(self):
"""Computes the exact bounding box of an outline.
Returns:
A tuple of ``(xMin, yMin, xMax, yMax)``.
"""
bbox = FT_BBox()
outline = self.outline()
FT_Outline_Get_BBox(ctypes.byref(outline), ctypes.byref(bbox))
return (bbox.xMin / 64.0, ... | Computes the exact bounding box of an outline.
Returns:
A tuple of ``(xMin, yMin, xMax, yMax)``.
| bbox | python | fonttools/fonttools | Lib/fontTools/pens/freetypePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/freetypePen.py | MIT |
def setTestPoint(self, testPoint, evenOdd=False):
"""Set the point to test. Call this _before_ the outline gets drawn."""
self.testPoint = testPoint
self.evenOdd = evenOdd
self.firstPoint = None
self.intersectionCount = 0 | Set the point to test. Call this _before_ the outline gets drawn. | setTestPoint | python | fonttools/fonttools | Lib/fontTools/pens/pointInsidePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointInsidePen.py | MIT |
def getResult(self):
"""After the shape has been drawn, getResult() returns True if the test
point lies within the (black) shape, and False if it doesn't.
"""
winding = self.getWinding()
if self.evenOdd:
result = winding % 2
else: # non-zero
resul... | After the shape has been drawn, getResult() returns True if the test
point lies within the (black) shape, and False if it doesn't.
| getResult | python | fonttools/fonttools | Lib/fontTools/pens/pointInsidePen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointInsidePen.py | MIT |
def addPoint(
self,
pt: Tuple[float, float],
segmentType: Optional[str] = None,
smooth: bool = False,
name: Optional[str] = None,
identifier: Optional[str] = None,
**kwargs: Any,
) -> None:
"""Add a point to the current sub path."""
raise NotIm... | Add a point to the current sub path. | addPoint | python | fonttools/fonttools | Lib/fontTools/pens/pointPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointPen.py | MIT |
def addVarComponent(
self,
glyphName: str,
transformation: DecomposedTransform,
location: Dict[str, float],
identifier: Optional[str] = None,
**kwargs: Any,
) -> None:
"""Add a VarComponent sub glyph. The 'transformation' argument
must be a DecomposedT... | Add a VarComponent sub glyph. The 'transformation' argument
must be a DecomposedTransform from the fontTools.misc.transform module,
and the 'location' argument must be a dictionary mapping axis tags
to their locations.
| addVarComponent | python | fonttools/fonttools | Lib/fontTools/pens/pointPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointPen.py | MIT |
def __init__(
self,
glyphSet,
*args,
skipMissingComponents=None,
reverseFlipped=False,
**kwargs,
):
"""Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced
as components are looked up by their name.
If the optional 'reve... | Takes a 'glyphSet' argument (dict), in which the glyphs that are referenced
as components are looked up by their name.
If the optional 'reverseFlipped' argument is True, components whose transformation
matrix has a negative determinant will be decomposed with a reversed path direction
t... | __init__ | python | fonttools/fonttools | Lib/fontTools/pens/pointPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointPen.py | MIT |
def addComponent(self, baseGlyphName, transformation, identifier=None, **kwargs):
"""Transform the points of the base glyph and draw it onto self.
The `identifier` parameter and any extra kwargs are ignored.
"""
from fontTools.pens.transformPen import TransformPointPen
try:
... | Transform the points of the base glyph and draw it onto self.
The `identifier` parameter and any extra kwargs are ignored.
| addComponent | python | fonttools/fonttools | Lib/fontTools/pens/pointPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/pointPen.py | MIT |
def lerpRecordings(recording1, recording2, factor=0.5):
"""Linearly interpolate between two recordings. The recordings
must be decomposed, i.e. they must not contain any components.
Factor is typically between 0 and 1. 0 means the first recording,
1 means the second recording, and 0.5 means the average... | Linearly interpolate between two recordings. The recordings
must be decomposed, i.e. they must not contain any components.
Factor is typically between 0 and 1. 0 means the first recording,
1 means the second recording, and 0.5 means the average of the
two recordings. Other values are possible, and can ... | lerpRecordings | python | fonttools/fonttools | Lib/fontTools/pens/recordingPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/recordingPen.py | MIT |
def reversedContour(contour, outputImpliedClosingLine=False):
"""Generator that takes a list of pen's (operator, operands) tuples,
and yields them with the winding direction reversed.
"""
if not contour:
return # nothing to do, stop iteration
# valid contours must have at least a starting ... | Generator that takes a list of pen's (operator, operands) tuples,
and yields them with the winding direction reversed.
| reversedContour | python | fonttools/fonttools | Lib/fontTools/pens/reverseContourPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/reverseContourPen.py | MIT |
def main(args):
"""Report font glyph shape geometricsl statistics"""
if args is None:
import sys
args = sys.argv[1:]
import argparse
parser = argparse.ArgumentParser(
"fonttools pens.statisticsPen",
description="Report font glyph shape geometricsl statistics",
)
... | Report font glyph shape geometricsl statistics | main | python | fonttools/fonttools | Lib/fontTools/pens/statisticsPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/statisticsPen.py | MIT |
def _moveTo(self, pt):
"""
>>> pen = SVGPathPen(None)
>>> pen.moveTo((0, 0))
>>> pen._commands
['M0 0']
>>> pen = SVGPathPen(None)
>>> pen.moveTo((10, 0))
>>> pen._commands
['M10 0']
>>> pen = SVGPathPen(None)
>>> pen.moveTo((0, 1... |
>>> pen = SVGPathPen(None)
>>> pen.moveTo((0, 0))
>>> pen._commands
['M0 0']
>>> pen = SVGPathPen(None)
>>> pen.moveTo((10, 0))
>>> pen._commands
['M10 0']
>>> pen = SVGPathPen(None)
>>> pen.moveTo((0, 10))
>>> pen._commands
... | _moveTo | python | fonttools/fonttools | Lib/fontTools/pens/svgPathPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py | MIT |
def _lineTo(self, pt):
"""
# duplicate point
>>> pen = SVGPathPen(None)
>>> pen.moveTo((10, 10))
>>> pen.lineTo((10, 10))
>>> pen._commands
['M10 10']
# vertical line
>>> pen = SVGPathPen(None)
>>> pen.moveTo((10, 10))
>>> pen.line... |
# duplicate point
>>> pen = SVGPathPen(None)
>>> pen.moveTo((10, 10))
>>> pen.lineTo((10, 10))
>>> pen._commands
['M10 10']
# vertical line
>>> pen = SVGPathPen(None)
>>> pen.moveTo((10, 10))
>>> pen.lineTo((10, 0))
>>> pen._comma... | _lineTo | python | fonttools/fonttools | Lib/fontTools/pens/svgPathPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py | MIT |
def _curveToOne(self, pt1, pt2, pt3):
"""
>>> pen = SVGPathPen(None)
>>> pen.curveTo((10, 20), (30, 40), (50, 60))
>>> pen._commands
['C10 20 30 40 50 60']
"""
t = "C"
t += pointToString(pt1, self._ntos) + " "
t += pointToString(pt2, self._ntos) + ... |
>>> pen = SVGPathPen(None)
>>> pen.curveTo((10, 20), (30, 40), (50, 60))
>>> pen._commands
['C10 20 30 40 50 60']
| _curveToOne | python | fonttools/fonttools | Lib/fontTools/pens/svgPathPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py | MIT |
def _qCurveToOne(self, pt1, pt2):
"""
>>> pen = SVGPathPen(None)
>>> pen.qCurveTo((10, 20), (30, 40))
>>> pen._commands
['Q10 20 30 40']
>>> from fontTools.misc.roundTools import otRound
>>> pen = SVGPathPen(None, ntos=lambda v: str(otRound(v)))
>>> pen.qC... |
>>> pen = SVGPathPen(None)
>>> pen.qCurveTo((10, 20), (30, 40))
>>> pen._commands
['Q10 20 30 40']
>>> from fontTools.misc.roundTools import otRound
>>> pen = SVGPathPen(None, ntos=lambda v: str(otRound(v)))
>>> pen.qCurveTo((3, 3), (7, 5), (11, 4))
>>> p... | _qCurveToOne | python | fonttools/fonttools | Lib/fontTools/pens/svgPathPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py | MIT |
def _closePath(self):
"""
>>> pen = SVGPathPen(None)
>>> pen.closePath()
>>> pen._commands
['Z']
"""
self._commands.append("Z")
self._lastCommand = "Z"
self._lastX = self._lastY = None |
>>> pen = SVGPathPen(None)
>>> pen.closePath()
>>> pen._commands
['Z']
| _closePath | python | fonttools/fonttools | Lib/fontTools/pens/svgPathPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py | MIT |
def _endPath(self):
"""
>>> pen = SVGPathPen(None)
>>> pen.endPath()
>>> pen._commands
[]
"""
self._lastCommand = None
self._lastX = self._lastY = None |
>>> pen = SVGPathPen(None)
>>> pen.endPath()
>>> pen._commands
[]
| _endPath | python | fonttools/fonttools | Lib/fontTools/pens/svgPathPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py | MIT |
def main(args=None):
"""Generate per-character SVG from font and text"""
if args is None:
import sys
args = sys.argv[1:]
from fontTools.ttLib import TTFont
import argparse
parser = argparse.ArgumentParser(
"fonttools pens.svgPathPen", description="Generate SVG from text"
... | Generate per-character SVG from font and text | main | python | fonttools/fonttools | Lib/fontTools/pens/svgPathPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/svgPathPen.py | MIT |
def __init__(self, outPen, transformation):
"""The 'outPen' argument is another pen object. It will receive the
transformed coordinates. The 'transformation' argument can either
be a six-tuple, or a fontTools.misc.transform.Transform object.
"""
super(TransformPen, self).__init__... | The 'outPen' argument is another pen object. It will receive the
transformed coordinates. The 'transformation' argument can either
be a six-tuple, or a fontTools.misc.transform.Transform object.
| __init__ | python | fonttools/fonttools | Lib/fontTools/pens/transformPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/transformPen.py | MIT |
def __init__(self, outPointPen, transformation):
"""The 'outPointPen' argument is another point pen object.
It will receive the transformed coordinates.
The 'transformation' argument can either be a six-tuple, or a
fontTools.misc.transform.Transform object.
"""
super().__... | The 'outPointPen' argument is another point pen object.
It will receive the transformed coordinates.
The 'transformation' argument can either be a six-tuple, or a
fontTools.misc.transform.Transform object.
| __init__ | python | fonttools/fonttools | Lib/fontTools/pens/transformPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/transformPen.py | MIT |
def glyph(
self,
componentFlags: int = 0x04,
dropImpliedOnCurves: bool = False,
*,
round: Callable[[float], int] = otRound,
) -> Glyph:
"""
Returns a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.
Args:
componentFlags: Flags t... |
Returns a :py:class:`~._g_l_y_f.Glyph` object representing the glyph.
Args:
componentFlags: Flags to use for component glyphs. (default: 0x04)
dropImpliedOnCurves: Whether to remove implied-oncurve points. (default: False)
| glyph | python | fonttools/fonttools | Lib/fontTools/pens/ttGlyphPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/ttGlyphPen.py | MIT |
def addPoint(
self,
pt: Tuple[float, float],
segmentType: Optional[str] = None,
smooth: bool = False,
name: Optional[str] = None,
identifier: Optional[str] = None,
**kwargs: Any,
) -> None:
"""
Add a point to the current sub path.
"""
... |
Add a point to the current sub path.
| addPoint | python | fonttools/fonttools | Lib/fontTools/pens/ttGlyphPen.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/pens/ttGlyphPen.py | MIT |
def _main(args=None):
"""Convert an OpenType font from quadratic to cubic curves"""
parser = argparse.ArgumentParser(prog="qu2cu")
parser.add_argument("--version", action="version", version=fontTools.__version__)
parser.add_argument(
"infiles",
nargs="+",
metavar="INPUT",
... | Convert an OpenType font from quadratic to cubic curves | _main | python | fonttools/fonttools | Lib/fontTools/qu2cu/cli.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/cli.py | MIT |
def cubic_farthest_fit_inside(p0, p1, p2, p3, tolerance):
"""Check if a cubic Bezier lies within a given distance of the origin.
"Origin" means *the* origin (0,0), not the start of the curve. Note that no
checks are made on the start and end positions of the curve; this function
only checks the inside ... | Check if a cubic Bezier lies within a given distance of the origin.
"Origin" means *the* origin (0,0), not the start of the curve. Note that no
checks are made on the start and end positions of the curve; this function
only checks the inside of the curve.
Args:
p0 (complex): Start point of cur... | cubic_farthest_fit_inside | python | fonttools/fonttools | Lib/fontTools/qu2cu/qu2cu.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py | MIT |
def elevate_quadratic(p0, p1, p2):
"""Given a quadratic bezier curve, return its degree-elevated cubic."""
# https://pomax.github.io/bezierinfo/#reordering
p1_2_3 = p1 * (2 / 3)
return (
p0,
(p0 * (1 / 3) + p1_2_3),
(p2 * (1 / 3) + p1_2_3),
p2,
) | Given a quadratic bezier curve, return its degree-elevated cubic. | elevate_quadratic | python | fonttools/fonttools | Lib/fontTools/qu2cu/qu2cu.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py | MIT |
def merge_curves(curves, start, n):
"""Give a cubic-Bezier spline, reconstruct one cubic-Bezier
that has the same endpoints and tangents and approxmates
the spline."""
# Reconstruct the t values of the cut segments
prod_ratio = 1.0
sum_ratio = 1.0
ts = [1]
for k in range(1, n):
... | Give a cubic-Bezier spline, reconstruct one cubic-Bezier
that has the same endpoints and tangents and approxmates
the spline. | merge_curves | python | fonttools/fonttools | Lib/fontTools/qu2cu/qu2cu.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py | MIT |
def quadratic_to_curves(
quads: List[List[Point]],
max_err: float = 0.5,
all_cubic: bool = False,
) -> List[Tuple[Point, ...]]:
"""Converts a connecting list of quadratic splines to a list of quadratic
and cubic curves.
A quadratic spline is specified as a list of points. Either each point is
... | Converts a connecting list of quadratic splines to a list of quadratic
and cubic curves.
A quadratic spline is specified as a list of points. Either each point is
a 2-tuple of X,Y coordinates, or each point is a complex number with
real/imaginary components representing X,Y coordinates.
The first... | quadratic_to_curves | python | fonttools/fonttools | Lib/fontTools/qu2cu/qu2cu.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py | MIT |
def spline_to_curves(q, costs, tolerance=0.5, all_cubic=False):
"""
q: quadratic spline with alternating on-curve / off-curve points.
costs: cumulative list of encoding cost of q in terms of number of
points that need to be encoded. Implied on-curve points do not
contribute to the cost. If all... |
q: quadratic spline with alternating on-curve / off-curve points.
costs: cumulative list of encoding cost of q in terms of number of
points that need to be encoded. Implied on-curve points do not
contribute to the cost. If all points need to be encoded, then
costs will be range(1, len(q)+1)... | spline_to_curves | python | fonttools/fonttools | Lib/fontTools/qu2cu/qu2cu.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/qu2cu/qu2cu.py | MIT |
def _add_method(*clazzes):
"""Returns a decorator function that adds a new method to one or
more classes."""
def wrapper(method):
done = []
for clazz in clazzes:
if clazz in done:
continue # Support multiple names of a clazz
done.append(clazz)
... | Returns a decorator function that adds a new method to one or
more classes. | _add_method | python | fonttools/fonttools | Lib/fontTools/subset/util.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/util.py | MIT |
def subset(self, glyphs):
"""Returns ascending list of remaining coverage values."""
indices = self.intersect(glyphs)
self.glyphs = [g for g in self.glyphs if g in glyphs]
return indices | Returns ascending list of remaining coverage values. | subset | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def intersect(self, glyphs):
"""Returns ascending list of matching class values."""
return _uniq_sort(
([0] if any(g not in self.classDefs for g in glyphs) else [])
+ [v for g, v in self.classDefs.items() if g in glyphs]
) | Returns ascending list of matching class values. | intersect | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def intersect_class(self, glyphs, klass):
"""Returns set of glyphs matching class."""
if klass == 0:
return set(g for g in glyphs if g not in self.classDefs)
return set(g for g, v in self.classDefs.items() if v == klass and g in glyphs) | Returns set of glyphs matching class. | intersect_class | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def subset(self, glyphs, remap=False, useClass0=True):
"""Returns ascending list of remaining classes."""
self.classDefs = {g: v for g, v in self.classDefs.items() if g in glyphs}
# Note: while class 0 has the special meaning of "not matched",
# if no glyph will ever /not match/, we can optimize class 0... | Returns ascending list of remaining classes. | subset | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def neuter_lookups(self, lookup_indices):
"""Sets lookups not in lookup_indices to None."""
self.ensureDecompiled()
self.Lookup = [
l if i in lookup_indices else None for i, l in enumerate(self.Lookup)
] | Sets lookups not in lookup_indices to None. | neuter_lookups | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def closure_lookups(self, lookup_indices):
"""Returns sorted index of all lookups reachable from lookup_indices."""
lookup_indices = _uniq_sort(lookup_indices)
recurse = lookup_indices
while True:
recurse_lookups = sum(
(self.Lookup[i].collect_lookups() for i in recurse if i < self.L... | Returns sorted index of all lookups reachable from lookup_indices. | closure_lookups | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def subset_lookups(self, lookup_indices):
""" "Returns True if feature is non-empty afterwards."""
self.LookupListIndex = [l for l in self.LookupListIndex if l in lookup_indices]
# Now map them.
self.LookupListIndex = [lookup_indices.index(l) for l in self.LookupListIndex]
self.LookupCount = len(sel... | "Returns True if feature is non-empty afterwards. | subset_lookups | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def subset_lookups(self, lookup_indices):
"""Returns the indices of nonempty features."""
# Note: Never ever drop feature 'pref', even if it's empty.
# HarfBuzz chooses shaper for Khmer based on presence of this
# feature. See thread at:
# http://lists.freedesktop.org/archives/harfbuzz/2012-November... | Returns the indices of nonempty features. | subset_lookups | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def subset_lookups(self, lookup_indices):
"""Returns the indices of nonempty features."""
return [
r.FeatureIndex
for r in self.SubstitutionRecord
if r.Feature.subset_lookups(lookup_indices)
] | Returns the indices of nonempty features. | subset_lookups | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def subset_lookups(self, lookup_indices):
"""Returns the indices of nonempty features."""
return sum(
(
f.FeatureTableSubstitution.subset_lookups(lookup_indices)
for f in self.FeatureVariationRecord
),
[],
) | Returns the indices of nonempty features. | subset_lookups | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def subset_lookups(self, lookup_indices):
"""Retains specified lookups, then removes empty features, language
systems, and scripts."""
if self.table.LookupList:
self.table.LookupList.subset_lookups(lookup_indices)
if self.table.FeatureList:
feature_indices = self.table.FeatureList.subset... | Retains specified lookups, then removes empty features, language
systems, and scripts. | subset_lookups | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def prune_lookups(self, remap=True):
"""Remove (default) or neuter unreferenced lookups"""
if self.table.ScriptList:
feature_indices = self.table.ScriptList.collect_features()
else:
feature_indices = []
if self.table.FeatureList:
lookup_indices = self.table.FeatureList.collect_lo... | Remove (default) or neuter unreferenced lookups | prune_lookups | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def _remap_select_name_ids(font: ttLib.TTFont, needRemapping: set[int]) -> None:
"""Remap a set of IDs so that the originals can be safely scrambled or
dropped.
For each name record whose name id is in the `needRemapping` set, make a copy
and allocate a new unused name id in the font-specific range (> ... | Remap a set of IDs so that the originals can be safely scrambled or
dropped.
For each name record whose name id is in the `needRemapping` set, make a copy
and allocate a new unused name id in the font-specific range (> 255).
Finally update references to these in the `fvar` and `STAT` tables.
| _remap_select_name_ids | python | fonttools/fonttools | Lib/fontTools/subset/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/subset/__init__.py | MIT |
def parse_path(pathdef, pen, current_pos=(0, 0), arc_class=EllipticalArc):
"""Parse SVG path definition (i.e. "d" attribute of <path> elements)
and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath
methods.
If 'current_pos' (2-float tuple) is provided, the initial moveTo will
be... | Parse SVG path definition (i.e. "d" attribute of <path> elements)
and call a 'pen' object's moveTo, lineTo, curveTo, qCurveTo and closePath
methods.
If 'current_pos' (2-float tuple) is provided, the initial moveTo will
be relative to that instead being absolute.
If the pen has an "arcTo" method, i... | parse_path | python | fonttools/fonttools | Lib/fontTools/svgLib/path/parser.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/svgLib/path/parser.py | MIT |
def read(path, onlyHeader=False):
"""reads any Type 1 font file, returns raw data"""
_, ext = os.path.splitext(path)
ext = ext.lower()
creator, typ = getMacCreatorAndType(path)
if typ == "LWFN":
return readLWFN(path, onlyHeader), "LWFN"
if ext == ".pfb":
return readPFB(path, only... | reads any Type 1 font file, returns raw data | read | python | fonttools/fonttools | Lib/fontTools/t1Lib/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/t1Lib/__init__.py | MIT |
def readLWFN(path, onlyHeader=False):
"""reads an LWFN font file, returns raw data"""
from fontTools.misc.macRes import ResourceReader
reader = ResourceReader(path)
try:
data = []
for res in reader.get("POST", []):
code = byteord(res.data[0])
if byteord(res.data[... | reads an LWFN font file, returns raw data | readLWFN | python | fonttools/fonttools | Lib/fontTools/t1Lib/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/t1Lib/__init__.py | MIT |
def readPFB(path, onlyHeader=False):
"""reads a PFB font file, returns raw data"""
data = []
with open(path, "rb") as f:
while True:
if f.read(1) != bytechr(128):
raise T1Error("corrupt PFB file")
code = byteord(f.read(1))
if code in [1, 2]:
... | reads a PFB font file, returns raw data | readPFB | python | fonttools/fonttools | Lib/fontTools/t1Lib/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/t1Lib/__init__.py | MIT |
def readOther(path):
"""reads any (font) file, returns raw data"""
with open(path, "rb") as f:
data = f.read()
assertType1(data)
chunks = findEncryptedChunks(data)
data = []
for isEncrypted, chunk in chunks:
if isEncrypted and isHex(chunk[:4]):
data.append(deHexString... | reads any (font) file, returns raw data | readOther | python | fonttools/fonttools | Lib/fontTools/t1Lib/__init__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/t1Lib/__init__.py | MIT |
def getSFNTResIndices(path):
"""Determine whether a file has a 'sfnt' resource fork or not."""
try:
reader = ResourceReader(path)
indices = reader.getIndices("sfnt")
reader.close()
return indices
except ResourceError:
return [] | Determine whether a file has a 'sfnt' resource fork or not. | getSFNTResIndices | python | fonttools/fonttools | Lib/fontTools/ttLib/macUtils.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/macUtils.py | MIT |
def openTTFonts(path):
"""Given a pathname, return a list of TTFont objects. In the case
of a flat TTF/OTF file, the list will contain just one font object;
but in the case of a Mac font suitcase it will contain as many
font objects as there are sfnt resources in the file.
"""
from fontTools imp... | Given a pathname, return a list of TTFont objects. In the case
of a flat TTF/OTF file, the list will contain just one font object;
but in the case of a Mac font suitcase it will contain as many
font objects as there are sfnt resources in the file.
| openTTFonts | python | fonttools/fonttools | Lib/fontTools/ttLib/macUtils.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/macUtils.py | MIT |
def removeOverlaps(
font: ttFont.TTFont,
glyphNames: Optional[Iterable[str]] = None,
removeHinting: bool = True,
ignoreErrors: bool = False,
*,
removeUnusedSubroutines: bool = True,
) -> None:
"""Simplify glyphs in TTFont by merging overlapping contours.
Overlapping components are first... | Simplify glyphs in TTFont by merging overlapping contours.
Overlapping components are first decomposed to simple contours, then merged.
Currently this only works for fonts with 'glyf' or 'CFF ' tables.
Raises NotImplementedError if 'glyf' or 'CFF ' tables are absent.
Note that removing overlaps inval... | removeOverlaps | python | fonttools/fonttools | Lib/fontTools/ttLib/removeOverlaps.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/removeOverlaps.py | MIT |
def main(args=None):
"""Simplify glyphs in TTFont by merging overlapping contours."""
import argparse
parser = argparse.ArgumentParser(
"fonttools ttLib.removeOverlaps", description=__doc__
)
parser.add_argument("input", metavar="INPUT.ttf", help="Input font file")
parser.add_argument... | Simplify glyphs in TTFont by merging overlapping contours. | main | python | fonttools/fonttools | Lib/fontTools/ttLib/removeOverlaps.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/removeOverlaps.py | MIT |
def scale_upem(font, new_upem):
"""Change the units-per-EM of font to the new value."""
upem = font["head"].unitsPerEm
visitor = ScalerVisitor(new_upem / upem)
visitor.visit(font) | Change the units-per-EM of font to the new value. | scale_upem | python | fonttools/fonttools | Lib/fontTools/ttLib/scaleUpem.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/scaleUpem.py | MIT |
def main(args=None):
"""Change the units-per-EM of fonts"""
if args is None:
import sys
args = sys.argv[1:]
from fontTools.ttLib import TTFont
from fontTools.misc.cliTools import makeOutputFileName
import argparse
parser = argparse.ArgumentParser(
"fonttools ttLib.sca... | Change the units-per-EM of fonts | main | python | fonttools/fonttools | Lib/fontTools/ttLib/scaleUpem.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/scaleUpem.py | MIT |
def __new__(cls, *args, **kwargs):
"""Return an instance of the SFNTReader sub-class which is compatible
with the input file type.
"""
if args and cls is SFNTReader:
infile = args[0]
infile.seek(0)
sfntVersion = Tag(infile.read(4))
infile.s... | Return an instance of the SFNTReader sub-class which is compatible
with the input file type.
| __new__ | python | fonttools/fonttools | Lib/fontTools/ttLib/sfnt.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py | MIT |
def compress(data, level=ZLIB_COMPRESSION_LEVEL):
"""Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True,
zopfli is used instead of the zlib module.
The compression 'level' must be between 0 and 9. 1 gives best speed,
9 gives best compression (0 gives no compression at all).
The default... | Compress 'data' to Zlib format. If 'USE_ZOPFLI' variable is True,
zopfli is used instead of the zlib module.
The compression 'level' must be between 0 and 9. 1 gives best speed,
9 gives best compression (0 gives no compression at all).
The default value is a compromise between speed and compression (6).... | compress | python | fonttools/fonttools | Lib/fontTools/ttLib/sfnt.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py | MIT |
def __new__(cls, *args, **kwargs):
"""Return an instance of the SFNTWriter sub-class which is compatible
with the specified 'flavor'.
"""
flavor = None
if kwargs and "flavor" in kwargs:
flavor = kwargs["flavor"]
elif args and len(args) > 3:
flavor ... | Return an instance of the SFNTWriter sub-class which is compatible
with the specified 'flavor'.
| __new__ | python | fonttools/fonttools | Lib/fontTools/ttLib/sfnt.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py | MIT |
def __setitem__(self, tag, data):
"""Write raw table data to disk."""
if tag in self.tables:
raise TTLibError("cannot rewrite '%s' table" % tag)
entry = self.DirectoryEntry()
entry.tag = tag
entry.offset = self.nextTableOffset
if tag == "head":
en... | Write raw table data to disk. | __setitem__ | python | fonttools/fonttools | Lib/fontTools/ttLib/sfnt.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py | MIT |
def close(self):
"""All tables must have been written to disk. Now write the
directory.
"""
tables = sorted(self.tables.items())
if len(tables) != self.numTables:
raise TTLibError(
"wrong number of tables; expected %d, found %d"
% (self... | All tables must have been written to disk. Now write the
directory.
| close | python | fonttools/fonttools | Lib/fontTools/ttLib/sfnt.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py | MIT |
def calcChecksum(data):
"""Calculate the checksum for an arbitrary block of data.
If the data length is not a multiple of four, it assumes
it is to be padded with null byte.
>>> print(calcChecksum(b"abcd"))
1633837924
>>> print(calcChecksum(b"abcdxyz"))
3655... | Calculate the checksum for an arbitrary block of data.
If the data length is not a multiple of four, it assumes
it is to be padded with null byte.
>>> print(calcChecksum(b"abcd"))
1633837924
>>> print(calcChecksum(b"abcdxyz"))
3655064932
| calcChecksum | python | fonttools/fonttools | Lib/fontTools/ttLib/sfnt.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/sfnt.py | MIT |
def save(self, file, shareTables=True):
"""Save the font to disk. Similarly to the constructor,
the 'file' argument can be either a pathname or a writable
file object.
"""
if not hasattr(file, "write"):
final = None
file = open(file, "wb")
else:
... | Save the font to disk. Similarly to the constructor,
the 'file' argument can be either a pathname or a writable
file object.
| save | python | fonttools/fonttools | Lib/fontTools/ttLib/ttCollection.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttCollection.py | MIT |
def save(self, file, reorderTables=True):
"""Save the font to disk.
Args:
file: Similarly to the constructor, can be either a pathname or a writable
file object.
reorderTables (Option[bool]): If true (the default), reorder the tables,
... | Save the font to disk.
Args:
file: Similarly to the constructor, can be either a pathname or a writable
file object.
reorderTables (Option[bool]): If true (the default), reorder the tables,
sorting them by tag (recommended by the O... | save | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def _save(self, file, tableCache=None):
"""Internal function, to be shared by save() and TTCollection.save()"""
if self.recalcTimestamp and "head" in self:
self[
"head"
] # make sure 'head' is loaded so the recalculation is actually done
tags = list(sel... | Internal function, to be shared by save() and TTCollection.save() | _save | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def saveXML(self, fileOrPath, newlinestr="\n", **kwargs):
"""Export the font as TTX (an XML-based text file), or as a series of text
files when splitTables is true. In the latter case, the 'fileOrPath'
argument should be a path to a directory.
The 'tables' argument must either be false (... | Export the font as TTX (an XML-based text file), or as a series of text
files when splitTables is true. In the latter case, the 'fileOrPath'
argument should be a path to a directory.
The 'tables' argument must either be false (dump all tables) or a
list of tables to dump. The 'skipTables... | saveXML | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def importXML(self, fileOrPath, quiet=None):
"""Import a TTX file (an XML-based text format), so as to recreate
a font object.
"""
if quiet is not None:
deprecateArgument("quiet", "configure logging instead")
if "maxp" in self and "post" in self:
# Make s... | Import a TTX file (an XML-based text format), so as to recreate
a font object.
| importXML | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def has_key(self, tag):
"""Test if the table identified by ``tag`` is present in the font.
As well as this method, ``tag in font`` can also be used to determine the
presence of the table."""
if self.isLoaded(tag):
return True
elif self.reader and tag in self.reader:
... | Test if the table identified by ``tag`` is present in the font.
As well as this method, ``tag in font`` can also be used to determine the
presence of the table. | has_key | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.