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 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):
"""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 |
def keys(self):
"""Returns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table."""
keys = list(self.tables.keys())
if self.reader:
for key in list(self.reader.keys()):
if key not in keys:
keys.append(key)
if "GlyphOr... | Returns the list of tables in the font, along with the ``GlyphOrder`` pseudo-table. | keys | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def ensureDecompiled(self, recurse=None):
"""Decompile all the tables, even if a TTFont was opened in 'lazy' mode."""
for tag in self.keys():
table = self[tag]
if recurse is None:
recurse = self.lazy is not False
if recurse and hasattr(table, "ensureDe... | Decompile all the tables, even if a TTFont was opened in 'lazy' mode. | ensureDecompiled | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def get(self, tag, default=None):
"""Returns the table if it exists or (optionally) a default if it doesn't."""
try:
return self[tag]
except KeyError:
return default | Returns the table if it exists or (optionally) a default if it doesn't. | get | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def setGlyphOrder(self, glyphOrder):
"""Set the glyph order
Args:
glyphOrder ([str]): List of glyph names in order.
"""
self.glyphOrder = glyphOrder
if hasattr(self, "_reverseGlyphOrderDict"):
del self._reverseGlyphOrderDict
if self.isLoaded("... | Set the glyph order
Args:
glyphOrder ([str]): List of glyph names in order.
| setGlyphOrder | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getGlyphOrder(self):
"""Returns a list of glyph names ordered by their position in the font."""
try:
return self.glyphOrder
except AttributeError:
pass
if "CFF " in self:
cff = self["CFF "]
self.glyphOrder = cff.getGlyphOrder()
... | Returns a list of glyph names ordered by their position in the font. | getGlyphOrder | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getGlyphName(self, glyphID):
"""Returns the name for the glyph with the given ID.
If no name is available, synthesises one with the form ``glyphXXXXX``` where
```XXXXX`` is the zero-padded glyph ID.
"""
try:
return self.getGlyphOrder()[glyphID]
except Ind... | Returns the name for the glyph with the given ID.
If no name is available, synthesises one with the form ``glyphXXXXX``` where
```XXXXX`` is the zero-padded glyph ID.
| getGlyphName | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getGlyphNameMany(self, lst):
"""Converts a list of glyph IDs into a list of glyph names."""
glyphOrder = self.getGlyphOrder()
cnt = len(glyphOrder)
return [glyphOrder[gid] if gid < cnt else "glyph%.5d" % gid for gid in lst] | Converts a list of glyph IDs into a list of glyph names. | getGlyphNameMany | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getGlyphID(self, glyphName):
"""Returns the ID of the glyph with the given name."""
try:
return self.getReverseGlyphMap()[glyphName]
except KeyError:
if glyphName[:5] == "glyph":
try:
return int(glyphName[5:])
except... | Returns the ID of the glyph with the given name. | getGlyphID | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getGlyphIDMany(self, lst):
"""Converts a list of glyph names into a list of glyph IDs."""
d = self.getReverseGlyphMap()
try:
return [d[glyphName] for glyphName in lst]
except KeyError:
getGlyphID = self.getGlyphID
return [getGlyphID(glyphName) for ... | Converts a list of glyph names into a list of glyph IDs. | getGlyphIDMany | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getReverseGlyphMap(self, rebuild=False):
"""Returns a mapping of glyph names to glyph IDs."""
if rebuild or not hasattr(self, "_reverseGlyphOrderDict"):
self._buildReverseGlyphOrderDict()
return self._reverseGlyphOrderDict | Returns a mapping of glyph names to glyph IDs. | getReverseGlyphMap | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def _writeTable(self, tag, writer, done, tableCache=None):
"""Internal helper function for self.save(). Keeps track of
inter-table dependencies.
"""
if tag in done:
return
tableClass = getTableClass(tag)
for masterTable in tableClass.dependencies:
... | Internal helper function for self.save(). Keeps track of
inter-table dependencies.
| _writeTable | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getTableData(self, tag):
"""Returns the binary representation of a table.
If the table is currently loaded and in memory, the data is compiled to
binary and returned; if it is not currently loaded, the binary data is
read from the font file and returned.
"""
tag = Ta... | Returns the binary representation of a table.
If the table is currently loaded and in memory, the data is compiled to
binary and returned; if it is not currently loaded, the binary data is
read from the font file and returned.
| getTableData | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getGlyphSet(
self, preferCFF=True, location=None, normalized=False, recalcBounds=True
):
"""Return a generic GlyphSet, which is a dict-like object
mapping glyph names to glyph objects. The returned glyph objects
have a ``.draw()`` method that supports the Pen protocol, and will
... | Return a generic GlyphSet, which is a dict-like object
mapping glyph names to glyph objects. The returned glyph objects
have a ``.draw()`` method that supports the Pen protocol, and will
have an attribute named 'width'.
If the font is CFF-based, the outlines will be taken from the ``CFF... | getGlyphSet | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def normalizeLocation(self, location):
"""Normalize a ``location`` from the font's defined axes space (also
known as user space) into the normalized (-1..+1) space. It applies
``avar`` mapping if the font contains an ``avar`` table.
The ``location`` parameter should be a dictionary mapp... | Normalize a ``location`` from the font's defined axes space (also
known as user space) into the normalized (-1..+1) space. It applies
``avar`` mapping if the font contains an ``avar`` table.
The ``location`` parameter should be a dictionary mapping four-letter
variation tags to their fl... | normalizeLocation | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getBestCmap(
self,
cmapPreferences=(
(3, 10),
(0, 6),
(0, 4),
(3, 1),
(0, 3),
(0, 2),
(0, 1),
(0, 0),
),
):
"""Returns the 'best' Unicode cmap dictionary available in the font
... | Returns the 'best' Unicode cmap dictionary available in the font
or ``None``, if no Unicode cmap subtable is available.
By default it will search for the following (platformID, platEncID)
pairs in order::
(3, 10), # Windows Unicode full repertoire
... | getBestCmap | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getTableModule(tag):
"""Fetch the packer/unpacker module for a table.
Return None when no module is found.
"""
from . import tables
pyTag = tagToIdentifier(tag)
try:
__import__("fontTools.ttLib.tables." + pyTag)
except ImportError as err:
# If pyTag is found in the Impor... | Fetch the packer/unpacker module for a table.
Return None when no module is found.
| getTableModule | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def registerCustomTableClass(tag, moduleName, className=None):
"""Register a custom packer/unpacker class for a table.
The 'moduleName' must be an importable module. If no 'className'
is given, it is derived from the tag, for example it will be
``table_C_U_S_T_`` for a 'CUST' tag.
The registered t... | Register a custom packer/unpacker class for a table.
The 'moduleName' must be an importable module. If no 'className'
is given, it is derived from the tag, for example it will be
``table_C_U_S_T_`` for a 'CUST' tag.
The registered table class should be a subclass of
:py:class:`fontTools.ttLib.tabl... | registerCustomTableClass | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getCustomTableClass(tag):
"""Return the custom table class for tag, if one has been registered
with 'registerCustomTableClass()'. Else return None.
"""
if tag not in _customTableRegistry:
return None
import importlib
moduleName, className = _customTableRegistry[tag]
module = imp... | Return the custom table class for tag, if one has been registered
with 'registerCustomTableClass()'. Else return None.
| getCustomTableClass | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getTableClass(tag):
"""Fetch the packer/unpacker class for a table."""
tableClass = getCustomTableClass(tag)
if tableClass is not None:
return tableClass
module = getTableModule(tag)
if module is None:
from .tables.DefaultTable import DefaultTable
return DefaultTable
... | Fetch the packer/unpacker class for a table. | getTableClass | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def getClassTag(klass):
"""Fetch the table tag for a class object."""
name = klass.__name__
assert name[:6] == "table_"
name = name[6:] # Chop 'table_'
return identifierToTag(name) | Fetch the table tag for a class object. | getClassTag | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def tagToIdentifier(tag):
"""Convert a table tag to a valid (but UGLY) python identifier,
as well as a filename that's guaranteed to be unique even on a
caseless file system. Each character is mapped to two characters.
Lowercase letters get an underscore before the letter, uppercase
letters get an u... | Convert a table tag to a valid (but UGLY) python identifier,
as well as a filename that's guaranteed to be unique even on a
caseless file system. Each character is mapped to two characters.
Lowercase letters get an underscore before the letter, uppercase
letters get an underscore after the letter. Trail... | tagToIdentifier | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def tagToXML(tag):
"""Similarly to tagToIdentifier(), this converts a TT tag
to a valid XML element name. Since XML element names are
case sensitive, this is a fairly simple/readable translation.
"""
import re
tag = Tag(tag)
if tag == "OS/2":
return "OS_2"
elif tag == "GlyphOrde... | Similarly to tagToIdentifier(), this converts a TT tag
to a valid XML element name. Since XML element names are
case sensitive, this is a fairly simple/readable translation.
| tagToXML | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def sortedTagList(tagList, tableOrder=None):
"""Return a sorted copy of tagList, sorted according to the OpenType
specification, or according to a custom tableOrder. If given and not
None, tableOrder needs to be a list of tag names.
"""
tagList = sorted(tagList)
if tableOrder is None:
if... | Return a sorted copy of tagList, sorted according to the OpenType
specification, or according to a custom tableOrder. If given and not
None, tableOrder needs to be a list of tag names.
| sortedTagList | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def reorderFontTables(inFile, outFile, tableOrder=None, checkChecksums=False):
"""Rewrite a font file, ordering the tables as recommended by the
OpenType specification 1.4.
"""
inFile.seek(0)
outFile.seek(0)
reader = SFNTReader(inFile, checkChecksums=checkChecksums)
writer = SFNTWriter(
... | Rewrite a font file, ordering the tables as recommended by the
OpenType specification 1.4.
| reorderFontTables | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def maxPowerOfTwo(x):
"""Return the highest exponent of two, so that
(2 ** exponent) <= x. Return 0 if x is 0.
"""
exponent = 0
while x:
x = x >> 1
exponent = exponent + 1
return max(exponent - 1, 0) | Return the highest exponent of two, so that
(2 ** exponent) <= x. Return 0 if x is 0.
| maxPowerOfTwo | python | fonttools/fonttools | Lib/fontTools/ttLib/ttFont.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttFont.py | MIT |
def draw(self, pen):
"""Draw the glyph onto ``pen``. See fontTools.pens.basePen for details
how that works.
"""
glyph, offset = self._getGlyphAndOffset()
with self.glyphSet.pushDepth() as depth:
if depth:
offset = 0 # Offset should only apply at top-... | Draw the glyph onto ``pen``. See fontTools.pens.basePen for details
how that works.
| draw | python | fonttools/fonttools | Lib/fontTools/ttLib/ttGlyphSet.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttGlyphSet.py | MIT |
def drawPoints(self, pen):
"""Draw the glyph onto ``pen``. See fontTools.pens.pointPen for details
how that works.
"""
glyph, offset = self._getGlyphAndOffset()
with self.glyphSet.pushDepth() as depth:
if depth:
offset = 0 # Offset should only apply ... | Draw the glyph onto ``pen``. See fontTools.pens.pointPen for details
how that works.
| drawPoints | python | fonttools/fonttools | Lib/fontTools/ttLib/ttGlyphSet.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/ttGlyphSet.py | MIT |
def __getitem__(self, tag):
"""Fetch the raw table data. Reconstruct transformed tables."""
entry = self.tables[Tag(tag)]
if not hasattr(entry, "data"):
if entry.transformed:
entry.data = self.reconstructTable(tag)
else:
entry.data = entry.... | Fetch the raw table data. Reconstruct transformed tables. | __getitem__ | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def reconstructTable(self, tag):
"""Reconstruct table named 'tag' from transformed data."""
entry = self.tables[Tag(tag)]
rawData = entry.loadData(self.transformBuffer)
if tag == "glyf":
# no need to pad glyph data when reconstructing
padding = self.padding if has... | Reconstruct table named 'tag' from transformed data. | reconstructTable | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _reconstructGlyf(self, data, padding=None):
"""Return recostructed glyf table data, and set the corresponding loca's
locations. Optionally pad glyph offsets to the specified number of bytes.
"""
self.ttFont["loca"] = WOFF2LocaTable()
glyfTable = self.ttFont["glyf"] = WOFF2Gly... | Return recostructed glyf table data, and set the corresponding loca's
locations. Optionally pad glyph offsets to the specified number of bytes.
| _reconstructGlyf | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _decompileTable(self, tag):
"""Decompile table data and store it inside self.ttFont."""
data = self[tag]
if self.ttFont.isLoaded(tag):
return self.ttFont[tag]
tableClass = getTableClass(tag)
table = tableClass(tag)
self.ttFont.tables[tag] = table
t... | Decompile table data and store it inside self.ttFont. | _decompileTable | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def __setitem__(self, tag, data):
"""Associate new entry named 'tag' with raw table data."""
if tag in self.tables:
raise TTLibError("cannot rewrite '%s' table" % tag)
if tag == "DSIG":
# always drop DSIG table, since the encoding process can invalidate it
sel... | Associate new entry named 'tag' with raw table data. | __setitem__ | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def close(self):
"""All tags must have been specified. Now write the table data and directory."""
if len(self.tables) != self.numTables:
raise TTLibError(
"wrong number of tables; expected %d, found %d"
% (self.numTables, len(self.tables))
)
... | All tags must have been specified. Now write the table data and directory. | close | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _normaliseGlyfAndLoca(self, padding=4):
"""Recompile glyf and loca tables, aligning glyph offsets to multiples of
'padding' size. Update the head table's 'indexToLocFormat' accordingly while
compiling loca.
"""
if self.sfntVersion == "OTTO":
return
for ta... | Recompile glyf and loca tables, aligning glyph offsets to multiples of
'padding' size. Update the head table's 'indexToLocFormat' accordingly while
compiling loca.
| _normaliseGlyfAndLoca | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _setHeadTransformFlag(self):
"""Set bit 11 of 'head' table flags to indicate that the font has undergone
a lossless modifying transform. Re-compile head table data."""
self._decompileTable("head")
self.ttFont["head"].flags |= 1 << 11
self._compileTable("head") | Set bit 11 of 'head' table flags to indicate that the font has undergone
a lossless modifying transform. Re-compile head table data. | _setHeadTransformFlag | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _decompileTable(self, tag):
"""Fetch table data, decompile it, and store it inside self.ttFont."""
tag = Tag(tag)
if tag not in self.tables:
raise TTLibError("missing required table: %s" % tag)
if self.ttFont.isLoaded(tag):
return
data = self.tables[ta... | Fetch table data, decompile it, and store it inside self.ttFont. | _decompileTable | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _calcSFNTChecksumsLengthsAndOffsets(self):
"""Compute the 'original' SFNT checksums, lengths and offsets for checksum
adjustment calculation. Return the total size of the uncompressed font.
"""
offset = sfntDirectorySize + sfntDirectoryEntrySize * len(self.tables)
for tag, en... | Compute the 'original' SFNT checksums, lengths and offsets for checksum
adjustment calculation. Return the total size of the uncompressed font.
| _calcSFNTChecksumsLengthsAndOffsets | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def transformTable(self, tag):
"""Return transformed table data, or None if some pre-conditions aren't
met -- in which case, the non-transformed table data will be used.
"""
if tag == "loca":
data = b""
elif tag == "glyf":
for tag in ("maxp", "head", "loca... | Return transformed table data, or None if some pre-conditions aren't
met -- in which case, the non-transformed table data will be used.
| transformTable | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _calcTotalSize(self):
"""Calculate total size of WOFF2 font, including any meta- and/or private data."""
offset = self.directorySize
for entry in self.tables.values():
offset += len(entry.toString())
offset += self.totalCompressedSize
offset = (offset + 3) & ~3
... | Calculate total size of WOFF2 font, including any meta- and/or private data. | _calcTotalSize | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _calcFlavorDataOffsetsAndSize(self, start):
"""Calculate offsets and lengths for any meta- and/or private data."""
offset = start
data = self.flavorData
if data.metaData:
self.metaOrigLength = len(data.metaData)
self.metaOffset = offset
self.compre... | Calculate offsets and lengths for any meta- and/or private data. | _calcFlavorDataOffsetsAndSize | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _getVersion(self):
"""Return the WOFF2 font's (majorVersion, minorVersion) tuple."""
data = self.flavorData
if data.majorVersion is not None and data.minorVersion is not None:
return data.majorVersion, data.minorVersion
else:
# if None, return 'fontRevision' f... | Return the WOFF2 font's (majorVersion, minorVersion) tuple. | _getVersion | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def _writeFlavorData(self):
"""Write metadata and/or private data using appropiate padding."""
compressedMetaData = self.compressedMetaData
privData = self.flavorData.privData
if compressedMetaData and privData:
compressedMetaData = pad(compressedMetaData, size=4)
if ... | Write metadata and/or private data using appropiate padding. | _writeFlavorData | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def getKnownTagIndex(tag):
"""Return index of 'tag' in woff2KnownTags list. Return 63 if not found."""
for i in range(len(woff2KnownTags)):
if tag == woff2KnownTags[i]:
return i
return woff2UnknownTagIndex | Return index of 'tag' in woff2KnownTags list. Return 63 if not found. | getKnownTagIndex | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def transformed(self):
"""Return True if the table has any transformation, else return False."""
# For all tables in a font, except for 'glyf' and 'loca', the transformation
# version 0 indicates the null transform (where the original table data is
# passed directly to the Brotli compres... | Return True if the table has any transformation, else return False. | transformed | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def __init__(self, reader=None, data=None, transformedTables=None):
"""Data class that holds the WOFF2 header major/minor version, any
metadata or private data (as bytes strings), and the set of
table tags that have transformations applied (if reader is not None),
or will have once the W... | Data class that holds the WOFF2 header major/minor version, any
metadata or private data (as bytes strings), and the set of
table tags that have transformations applied (if reader is not None),
or will have once the WOFF2 font is compiled.
Args:
reader: an SFNTReader (or... | __init__ | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def unpackBase128(data):
r"""Read one to five bytes from UIntBase128-encoded input string, and return
a tuple containing the decoded integer plus any leftover data.
>>> unpackBase128(b'\x3f\x00\x00') == (63, b"\x00\x00")
True
>>> unpackBase128(b'\x8f\xff\xff\xff\x7f')[0] == 4294967295
True
... | Read one to five bytes from UIntBase128-encoded input string, and return
a tuple containing the decoded integer plus any leftover data.
>>> unpackBase128(b'\x3f\x00\x00') == (63, b"\x00\x00")
True
>>> unpackBase128(b'\x8f\xff\xff\xff\x7f')[0] == 4294967295
True
>>> unpackBase128(b'\x80\x80\x3f'... | unpackBase128 | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def base128Size(n):
"""Return the length in bytes of a UIntBase128-encoded sequence with value n.
>>> base128Size(0)
1
>>> base128Size(24567)
3
>>> base128Size(2**32-1)
5
"""
assert n >= 0
size = 1
while n >= 128:
size += 1
n >>= 7
return size | Return the length in bytes of a UIntBase128-encoded sequence with value n.
>>> base128Size(0)
1
>>> base128Size(24567)
3
>>> base128Size(2**32-1)
5
| base128Size | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def packBase128(n):
r"""Encode unsigned integer in range 0 to 2**32-1 (inclusive) to a string of
bytes using UIntBase128 variable-length encoding. Produce the shortest possible
encoding.
>>> packBase128(63) == b"\x3f"
True
>>> packBase128(2**32-1) == b'\x8f\xff\xff\xff\x7f'
True
"""
... | Encode unsigned integer in range 0 to 2**32-1 (inclusive) to a string of
bytes using UIntBase128 variable-length encoding. Produce the shortest possible
encoding.
>>> packBase128(63) == b"\x3f"
True
>>> packBase128(2**32-1) == b'\x8f\xff\xff\xff\x7f'
True
| packBase128 | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def unpack255UShort(data):
"""Read one to three bytes from 255UInt16-encoded input string, and return a
tuple containing the decoded integer plus any leftover data.
>>> unpack255UShort(bytechr(252))[0]
252
Note that some numbers (e.g. 506) can have multiple encodings:
>>> unpack255UShort(struc... | Read one to three bytes from 255UInt16-encoded input string, and return a
tuple containing the decoded integer plus any leftover data.
>>> unpack255UShort(bytechr(252))[0]
252
Note that some numbers (e.g. 506) can have multiple encodings:
>>> unpack255UShort(struct.pack("BB", 254, 0))[0]
506
... | unpack255UShort | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def pack255UShort(value):
r"""Encode unsigned integer in range 0 to 65535 (inclusive) to a bytestring
using 255UInt16 variable-length encoding.
>>> pack255UShort(252) == b'\xfc'
True
>>> pack255UShort(506) == b'\xfe\x00'
True
>>> pack255UShort(762) == b'\xfd\x02\xfa'
True
"""
if... | Encode unsigned integer in range 0 to 65535 (inclusive) to a bytestring
using 255UInt16 variable-length encoding.
>>> pack255UShort(252) == b'\xfc'
True
>>> pack255UShort(506) == b'\xfe\x00'
True
>>> pack255UShort(762) == b'\xfd\x02\xfa'
True
| pack255UShort | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def compress(input_file, output_file, transform_tables=None):
"""Compress OpenType font to WOFF2.
Args:
input_file: a file path, file or file-like object (open in binary mode)
containing an OpenType font (either CFF- or TrueType-flavored).
output_file: a file path, f... | Compress OpenType font to WOFF2.
Args:
input_file: a file path, file or file-like object (open in binary mode)
containing an OpenType font (either CFF- or TrueType-flavored).
output_file: a file path, file or file-like object where to save the
compres... | compress | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def decompress(input_file, output_file):
"""Decompress WOFF2 font to OpenType font.
Args:
input_file: a file path, file or file-like object (open in binary mode)
containing a compressed WOFF2 font.
output_file: a file path, file or file-like object where to save the
... | Decompress WOFF2 font to OpenType font.
Args:
input_file: a file path, file or file-like object (open in binary mode)
containing a compressed WOFF2 font.
output_file: a file path, file or file-like object where to save the
decompressed OpenType font.
... | decompress | python | fonttools/fonttools | Lib/fontTools/ttLib/woff2.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/woff2.py | MIT |
def main(args=None):
"""Open/save fonts with TTFont() or TTCollection()
./fonttools ttLib [-oFILE] [-yNUMBER] files...
If multiple files are given on the command-line,
they are each opened (as a font or collection),
and added to the font list.
If -o (output-file) argument is given, the font... | Open/save fonts with TTFont() or TTCollection()
./fonttools ttLib [-oFILE] [-yNUMBER] files...
If multiple files are given on the command-line,
they are each opened (as a font or collection),
and added to the font list.
If -o (output-file) argument is given, the font
list is then saved to t... | main | python | fonttools/fonttools | Lib/fontTools/ttLib/__main__.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/__main__.py | MIT |
def decompile(self, data, font):
"""Create an object from the binary data. Called automatically on access."""
from . import otTables
reader = OTTableReader(data, tableTag=self.tableTag)
tableClass = getattr(otTables, self.tableTag)
self.table = tableClass()
self.table.de... | Create an object from the binary data. Called automatically on access. | decompile | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def compile(self, font):
"""Compiles the table into binary. Called automatically on save."""
# General outline:
# Create a top-level OTTableWriter for the GPOS/GSUB table.
# Call the compile method for the the table
# for each 'converter' record in the table converter list
... | Compiles the table into binary. Called automatically on save. | compile | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def getDataLength(self):
"""Return the length of this table in bytes, without subtables."""
l = 0
for item in self.items:
if hasattr(item, "getCountData"):
l += item.size
elif hasattr(item, "subWriter"):
l += item.offsetSize
els... | Return the length of this table in bytes, without subtables. | getDataLength | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def getData(self):
"""Assemble the data for this writer/table, without subtables."""
items = list(self.items) # make a shallow copy
pos = self.pos
numItems = len(items)
for i in range(numItems):
item = items[i]
if hasattr(item, "subWriter"):
... | Assemble the data for this writer/table, without subtables. | getData | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def getDataForHarfbuzz(self):
"""Assemble the data for this writer/table with all offset field set to 0"""
items = list(self.items)
packFuncs = {2: packUShort, 3: packUInt24, 4: packULong}
for i, item in enumerate(items):
if hasattr(item, "subWriter"):
# Offse... | Assemble the data for this writer/table with all offset field set to 0 | getDataForHarfbuzz | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def getAllDataUsingHarfbuzz(self, tableTag):
"""The Whole table is represented as a Graph.
Assemble graph data and call Harfbuzz repacker to pack the table.
Harfbuzz repacker is faster and retain as much sub-table sharing as possible, see also:
https://github.com/harfbuzz/harfbuzz/blob/m... | The Whole table is represented as a Graph.
Assemble graph data and call Harfbuzz repacker to pack the table.
Harfbuzz repacker is faster and retain as much sub-table sharing as possible, see also:
https://github.com/harfbuzz/harfbuzz/blob/main/docs/repacker.md
The input format for hb.rep... | getAllDataUsingHarfbuzz | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def getAllData(self, remove_duplicate=True):
"""Assemble all data, including all subtables."""
if remove_duplicate:
internedTables = {}
self._doneWriting(internedTables)
tables = []
extTables = []
done = {}
self._gatherTables(tables, extTables, don... | Assemble all data, including all subtables. | getAllData | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def iterSubTables(self) -> Iterator[SubTableEntry]:
"""Yield (name, value, index) namedtuples for all subtables of current table.
A sub-table is an instance of BaseTable (or subclass thereof) that is a child
of self, the current parent table.
The tuples also contain the attribute name (... | Yield (name, value, index) namedtuples for all subtables of current table.
A sub-table is an instance of BaseTable (or subclass thereof) that is a child
of self, the current parent table.
The tuples also contain the attribute name (str) of the of parent table to get
a subtable, and opti... | iterSubTables | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def getVariableAttrs(cls: BaseTable, fmt: Optional[int] = None) -> Tuple[str]:
"""Return sequence of variable table field names (can be empty).
Attributes are deemed "variable" when their otData.py's description contain
'VarIndexBase + {offset}', e.g. COLRv1 PaintVar* tables.
"""
if not issubclass(... | Return sequence of variable table field names (can be empty).
Attributes are deemed "variable" when their otData.py's description contain
'VarIndexBase + {offset}', e.g. COLRv1 PaintVar* tables.
| getVariableAttrs | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otBase.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otBase.py | MIT |
def buildConverters(tableSpec, tableNamespace):
"""Given a table spec from otData.py, build a converter object for each
field of the table. This is called for each table in otData.py, and
the results are assigned to the corresponding class in otTables.py."""
converters = []
convertersByName = {}
... | Given a table spec from otData.py, build a converter object for each
field of the table. This is called for each table in otData.py, and
the results are assigned to the corresponding class in otTables.py. | buildConverters | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otConverters.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otConverters.py | MIT |
def readArray(self, reader, font, tableDict, count):
"""Read an array of values from the reader."""
lazy = font.lazy and count > 8
if lazy:
recordSize = self.getRecordSize(reader)
if recordSize is NotImplemented:
lazy = False
if not lazy:
... | Read an array of values from the reader. | readArray | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otConverters.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otConverters.py | MIT |
def getVarIndexOffset(self) -> Optional[int]:
"""If description has `VarIndexBase + {offset}`, return the offset else None."""
m = self.varIndexBasePlusOffsetRE.search(self.description)
if not m:
return None
return int(m.group(1)) | If description has `VarIndexBase + {offset}`, return the offset else None. | getVarIndexOffset | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otConverters.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otConverters.py | MIT |
def _read_uint32var(data, i):
"""Read a variable-length number from data starting at index i.
Return the number and the next index.
"""
b0 = data[i]
if b0 < 0x80:
return b0, i + 1
elif b0 < 0xC0:
return (b0 - 0x80) << 8 | data[i + 1], i + 2
elif b0 < 0xE0:
return (b... | Read a variable-length number from data starting at index i.
Return the number and the next index.
| _read_uint32var | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otTables.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otTables.py | MIT |
def _write_uint32var(v):
"""Write a variable-length number.
Return the data.
"""
if v < 0x80:
return struct.pack(">B", v)
elif v < 0x4000:
return struct.pack(">H", (v | 0x8000))
elif v < 0x200000:
return struct.pack(">L", (v | 0xC00000))[1:]
elif v < 0x10000000:
... | Write a variable-length number.
Return the data.
| _write_uint32var | python | fonttools/fonttools | Lib/fontTools/ttLib/tables/otTables.py | https://github.com/fonttools/fonttools/blob/master/Lib/fontTools/ttLib/tables/otTables.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.